﻿using Bifrost;
using DevComponents.DotNetBar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Drawing.Text;
using System.IO;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Web;
using System.Windows.Forms;
using System.Xml;
using TextEditor.TextDocument.Action;
using TextEditor.TextDocument.Element;
using TextEditor.TextDocument.frmWindow;
using ZYCommon;
using Bifrost.WcfSvr;

namespace TextEditor.TextDocument.Document
{
    public class ZYTextDocument : IDisposable, IZYViewDocument, IZYContentDocument
    {
        private bool bolEnableJumpPrint = false;  //是否续打
        private bool bolFormatAll;//- 新添加了 A-FormatUnLine
        private bool bolLastContentChangedFlag = false;
        protected int intJumpPrintPosition = 0;
        protected bool bolLoading = false;
        private bool bolLocked = false;//文档只读
        protected const string c_EditorVersion = "1.0";
        public bool ElementsDirty = false;
        private float fLineSpacing = 0f;
        private int intLogLevel = 0;
        protected int intUndoState = 0;
        private ArrayList myActions = new ArrayList();//模板编辑区的操作动作集合
        private object myAllElement = null;
        protected ArrayList myContainters = new ArrayList();
        private ZYContent myContent = new ZYContent();//模板编辑区的内容实例
        private A_ContentChangeLog myContentChangeLog = null;
        protected ZYTextElement myCurrentHoverElement = null;
        private ZYDataSource myDataSource = new ZYDataSource();
        private ZYTextContainer myDocumentElement = null;
        private ArrayList myElements = new ArrayList();
        private ZYVBScriptEngine myZYVBEngine;
        private ZYDocumentInfo myInfo = new ZYDocumentInfo();
        protected ZYKBBuffer myKBBuffer = null;
        protected ArrayList myLines = new ArrayList(100);
        protected UnderWriteMarkCollection myMarks = new UnderWriteMarkCollection();
        private UcEditorControl myOwnerControl = null;
        protected PrintPageCollection myPages = new PrintPageCollection();//当前模板编辑页的集合
        protected System.Drawing.Printing.PageSettings myPageSettings = new System.Drawing.Printing.PageSettings();
        private ArrayList myRedoList = new ArrayList();//记录下一步操作集合
        private ZYTextSaveLogCollection mySaveLogs = new ZYTextSaveLogCollection();
        protected ZYVBScriptElement myScript = new ZYVBScriptElement();
        private ArrayList myUndoList = new ArrayList();//记录上一步操作的集合
        protected NameValueList myVariables = new NameValueList();
        private DocumentView myView = new DocumentView();//模板编辑区的视图展示
        public KB_Item OwnerKBItem = null;
        public bool RefreshAllFlag = false;//全刷新的标识
        protected string[] strHideElementNames = null;
        protected string strToolTip = null;//提示消息的内容
        private Rectangle ToolTipBounds;//提示消息框的位置大小
        private int ToolTipImageIndex;//在对图片进行消息提示的图片索引     
        public StringFormat titleStringFormat = new StringFormat();
        public ArrayList signatures = new ArrayList();
        public event EventHandler OnContentChanged;//模板内容变化的事件
        public event JumpDivHandler OnJumpDiv;//收缩文本块的事件
        private ZYTextElement jumpElement = null;
        //public RealRTF.RTFExtend ff;
        private bool hidleNameTitle = true;
        private string englishNumFontStr = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private string englishHalf = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?!,./';:\"[]{}%*()_+^$#@!~";
        public static string numbers = "1234567890.:：-/,，。.〉》」』】〕〗！＂＇";
        public ZYMenus Menus = new ZYMenus();
        private DocSettings _setting = null;
        Dictionary<string, List<string>> sqlDiagnoseList = null;
        private int pageStartIndex = 0;
        public delegate void DrawPageHeader(Graphics g, Rectangle drawRegion, int pageIndex, PageHeaders splitStaterHeader, ZYTextDocument document);
        public event DrawPageHeader OnDrawPageHeader;
        public bool canCopyPaste = false;

        //病案评分
        public delegate void BackPFId(string id, int action);
        public event BackPFId OnBackPFId;

        public delegate void BackPFIdDoctor(string id);
        public event BackPFIdDoctor OnBackPfIdDoctor;

        public int PageStartIndex
        {
            get { return pageStartIndex; }
            set { pageStartIndex = value; }
        }

        public bool CanCopyPaste
        {
            get
            {
                return this.canCopyPaste;
            }

            set
            {
                this.canCopyPaste = value;
            }
        }

        /// <summary>
        /// 保存的文书信息
        /// </summary>
        public DocSettings Setting
        {
            get { return _setting; }
            set { _setting = value; }
        }

        //页眉信息
        private Dictionary<string, string> _pageHeader = null;
        public bool HidleNameTitle
        {
            get { return hidleNameTitle; }
            set { hidleNameTitle = value; }
        }

        public bool isSjyscf = false;
        public event EventHandler OnSelectionChanged;
        public event EventHandler<BackEvenHandle> OnBackTextId;

        protected int intFooterHeight = 0;
        protected int intHeadHeight = 0;

        private SelectForm selectForm;
        public int flag = -1;
        public int saveFlag = -1;//判断是保存还是添加
        private UserInfo _us = new UserInfo();
        public UserInfo Us
        {
            get { return _us; }
            set { _us = value; }
        }

        public Dictionary<string, List<string>> SqlDiagnoseList
        {
            get
            {
                if (sqlDiagnoseList == null)
                    sqlDiagnoseList = new Dictionary<string, List<string>>();
                return sqlDiagnoseList;
            }
        }

        public SelectForm SelectForm
        {
            get { return selectForm; }
            set { selectForm = value; }
        }

        public ZYTextElement JumpElement
        {
            get { return jumpElement; }
            set { jumpElement = value; }
        }

        public ZYTextContainer GetContainer
        {
            get
            {
                return this.myDocumentElement;
            }
        }

        /// <summary>
        /// 构造函数 初始参数设置
        /// </summary>
        public ZYTextDocument()
        {
            this.Info.OwnerDocument = this;
            this.myContent.Document = this;
            this.myContent.Elements = this.myElements;
            this.InitActionList();
            this._setting = new DocSettings(this);
            this.myDocumentElement = new ZYTextDiv();
            this.myDocumentElement.OwnerDocument = this;
            this.RefreshElements();
            this.myView.Width = this.myPages.StandardWidth;
            this.mySaveLogs.OwnerDocument = this;
            this.myMarks.OwnerDocument = this;
            this.myScript.OwnerDocument = this;
            DocumentInit();
        }

        public decimal FromInchToCM(decimal inch)
        {
            return Math.Round((System.Convert.ToDecimal((inch / 100)) * System.Convert.ToDecimal(2.5400)), 2);  //Math.Round取两位小数
        }

        public void ChangedBapf(string id, int action)
        {
            if (this.OnBackPFId != null)
            {
                this.OnBackPFId(id, action);
            }
        }

        public void ChangedBapfDoctor(string id)
        {
            if (this.OnBackPfIdDoctor != null)
            {
                this.OnBackPfIdDoctor(id);
            }
        }

        public bool isHavePfDoctor()
        {
            if (this.OnBackPfIdDoctor != null)
                return true;
            return false;
        }

        public bool isHavePf()
        {
            if (this.OnBackPFId != null)
            {
                return true;
            }
            return false;
        }

        private bool enableShowAll = true;

        public bool EnableShowAll
        {
            get { return enableShowAll; }
            set { enableShowAll = value; }
        }


        public void DocumentInit()
        {
            //同仁
            if (this.Pages.Attributes.Count < 1)
            {
                try
                {
                    //double yincun = 2.54;
                    this.myPages.PaperWidth = GetTheThousandthsOfAnInch(2100);// PrinterUnitConvert.Convert(2100, PrinterUnit.HundredthsOfAMillimeter, PrinterUnit.ThousandthsOfAnInch); //Convert.ToInt32(21 / yincun * 100);//784;  //(int)(this.myPageSettings.PaperSize.Width * num);
                    this.myPages.PaperHeight = GetTheThousandthsOfAnInch(2970);// 1045;//s (int)(this.myPageSettings.PaperSize.Height * num);
                    this.myPages.LeftMargin = GetTheThousandthsOfAnInch(200);// Convert.ToInt32(2.5 / yincun * 100);//50;   //(int)(this.myPageSettings.Margins.Left * num);
                    this.myPages.TopMargin = GetTheThousandthsOfAnInch(450);// Convert.ToInt32(3.4 / yincun * 100);//130;   //(int)(this.myPageSettings.Margins.Top * num);
                    this.myPages.RightMargin = GetTheThousandthsOfAnInch(200); //Convert.ToInt32(1 / yincun * 100);// 50;  //(int)(this.myPageSettings.Margins.Right * num);
                    this.myPages.BottomMargin = GetTheThousandthsOfAnInch(200);//Convert.ToInt32(2.5 / yincun * 100);// 60; //(int)(this.myPageSettings.Margins.Bottom * num);        
                    this.myPages.TitleMarginTop = GetTheThousandthsOfAnInch(200);
                    this.myPages.PaperKindName = "A4";
                    titleStringFormat.Alignment = StringAlignment.Center;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        public static int GetTheThousandthsOfAnInch(int millimeter)
        {
            return PrinterUnitConvert.Convert(millimeter, PrinterUnit.HundredthsOfAMillimeter, PrinterUnit.ThousandthsOfAnInch);
        }

        public static int GetAnInchOfTheThousandths(int anInch)
        {
            return PrinterUnitConvert.Convert(anInch, PrinterUnit.ThousandthsOfAnInch, PrinterUnit.HundredthsOfAMillimeter);
        }

        /***
         * 返回文书ID
         */
        public void BackTextid(string id)
        {
            if (this.OnBackTextId != null)
            {
                BackEvenHandle be = new BackEvenHandle();
                be.Para = id;
                be.Style = 5;
                this.OnBackTextId(this, be);
            }
        }

        private bool isDeletedOk(int deleteType)
        {
            if (this.myContent.CurrentElement.Index > 0)
            {
                ZYTextElement ze = this.myContent.CurrentElement;
                if (ze.Index > 0)
                {
                    ZYTextElement ze2 = this.myContent.Elements[ze.Index - 1] as ZYTextElement;
                    if (ze.Parent is ZYTextDiv)
                    {
                        string title = (ze.Parent as ZYTextDiv).Title.ToString().Trim();
                        if (title != "")
                        {
                            if (title == "术前诊断"
                                || title == "术后诊断"
                                || title == "初步诊断"
                                || title == "补充诊断"
                                || title == "修正诊断"
                                || title == "修订诊断"
                                || title == "出院诊断"
                                || title == "死亡诊断")
                            {
                                return false;
                            }
                            //Bifrost.InPatientInfo tt = new InPatientInfo();  病人信息
                        }
                    }
                    if (deleteType == 0)
                    {
                        if (ze2.Parent is ZYTextDiv)
                        {
                            string title = (ze2.Parent as ZYTextDiv).Title.ToString().Trim();
                            if (title != "")
                            {
                                if (title == "术前诊断"
                                    || title == "术后诊断"
                                    || title == "初步诊断"
                                    || title == "补充诊断"
                                    || title == "修正诊断"
                                    || title == "修订诊断"
                                    || title == "出院诊断"
                                    || title == "死亡诊断")
                                {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// backSpace键
        /// </summary>
        public void _BackSpace()
        {
            if ((this.mySaveLogs == null) || (this.SaveLogs.Count == 1))
            {
                this.myInfo.LogicDelete = false;
            }
            else
            {
                this.myInfo.LogicDelete = true;
            }
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();

                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else
                {
                    this.myContent.DeletePreElement();
                    this.ContentChanged();
                }
                this.myContentChangeLog.strUndoName = "退格删除";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 复制
        /// </summary>
        /// <returns></returns>
        public bool _Copy()
        {
            try
            {
                if (this.Menus.PnlMenus.Visible == false)
                    return false;
                ArrayList selectElements = this.myContent.GetSelectElements();
                ZYTextElement.FixElementsForParent(selectElements);
                if ((selectElements != null) && (selectElements.Count > 0))
                {
                    DataObject data = new DataObject();
                    data.SetData(DataFormats.UnicodeText, ZYTextElement.GetElementsText(selectElements));
                    this.myInfo.SaveMode = 0;
                    XmlDocument document = new XmlDocument();
                    document.AppendChild(document.CreateElement("emrtextdocument2005"));
                    if (ZYTextElement.ElementsToXML(selectElements, document.DocumentElement))
                    {
                        string outerXml = document.DocumentElement.OuterXml;
                        XmlDocument oldDocument = new XmlDocument();
                        oldDocument.PreserveWhitespace = true;
                        oldDocument.LoadXml(outerXml);
                        XmlDocument newDocument = new XmlDocument();
                        newDocument.PreserveWhitespace = true;
                        newDocument.LoadXml("<emrtextdocument2005/>");
                        CreateNewXml(newDocument.DocumentElement, oldDocument.DocumentElement, 0);
                        if (this.Us.InpatientInfo != null)
                        {
                            XmlAttribute patient_attribute = newDocument.CreateAttribute("inpatient_id");
                            patient_attribute.Value = this.Us.InpatientInfo.Id.ToString();
                            newDocument.DocumentElement.Attributes.Append(patient_attribute);
                        }
                        data.SetData("emrtextdocument2005", newDocument.OuterXml);
                    }
                    Clipboard.SetDataObject(data, true);
                    return true;
                }
            }
            catch (Exception exception)
            {
                ZYErrorReport.Instance.SourceException = exception;
                ZYErrorReport.Instance.SourceObject = this;
                ZYErrorReport.Instance.UserMessage = "复制数据错误";
                ZYErrorReport.Instance.ReportError();
            }
            return false;
        }

        private string suporSign = "";
        /// <summary>
        /// 上级医师查房
        /// </summary>
        public string SuporSign
        {
            get { return suporSign; }
            set { suporSign = value; }
        }


        /// <summary>
        /// 过滤特殊
        /// </summary>
        /// <param name="xl"></param>
        /// <param name="element"></param>
        public void CreateNewXml(XmlElement xl, XmlElement element, int style)
        {
            foreach (XmlNode xml in element.ChildNodes)
            {
                if (xml is XmlElement)
                {
                    XmlElement elem = (XmlElement)xml;
                    if (!RemoveDeleteNode(elem, style))
                    {
                        XmlElement x = xl.OwnerDocument.CreateElement(xml.Name);
                        if (xml.ChildNodes.Count > 0)
                        {
                            CreateNewXml(x, elem, style);
                        }

                        foreach (XmlAttribute attribute in elem.Attributes)
                        {
                            if (attribute.Name == "creator" || attribute.Name == "operatercreater" || attribute.Name == "leftchars")
                            {
                                continue;
                            }
                            if (style == 10 && (attribute.Name == "candelete" || attribute.Name == "minlength"))
                            {
                                continue;
                            }
                            x.SetAttribute(attribute.Name, attribute.Value);
                        }
                        xl.AppendChild(x);
                    }
                }

                if (xml is XmlText)
                {
                    XmlText xtext = xl.OwnerDocument.CreateTextNode(xml.Value);
                    xl.AppendChild(xtext);
                }
                if (xml is XmlWhitespace)
                {
                    XmlWhitespace xspace = xl.OwnerDocument.CreateWhitespace(xml.Value);
                    xl.AppendChild(xspace);
                }
            }
        }

        public bool RemoveDeleteNode(XmlElement myElement, int style)
        {
            if (myElement.Attributes != null)
            {
                foreach (XmlAttribute attribute in myElement.Attributes)
                {
                    if (attribute.Name == "deleter")
                    {
                        return true;
                    }
                    switch (style)
                    {
                        case 0:
                            if (myElement.Name == "input")
                            {
                                if (attribute.Name == "name" && (attribute.Value.Contains("签名")))
                                {
                                    return true;
                                }
                            }
                            break;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 剪切
        /// </summary>
        public void _Cut()
        {
            if (!this.Locked)
            {
                this._Copy();
                this._Delete();
            }
        }

        /// <summary>
        /// 删除 -- delete键
        /// </summary>
        public void _Delete()
        {
            if (!isDeletedOk(1)) { return; };
            //**************判断文档时第几次打开，如果是第一次操作文档，则不自动保存痕迹，否则自动保存对文档的操作痕迹*************
            if ((this.mySaveLogs == null) || (this.SaveLogs.Count == 1))
            {
                this.myInfo.LogicDelete = false;
            }
            else
            {
                this.myInfo.LogicDelete = true;
            }
            //***************
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else
                {
                    int selectStart = this.myContent.SelectStart;
                    if ((this.myContent.DeleteCurrentElement() == 2))//****删除&& this.myInfo.ShowAll判断条件*****
                    {
                        this.Content.SetSelection(selectStart, 0);
                        this.ContentChanged();
                    }
                }
                this.myContentChangeLog.strUndoName = "删除元素";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        public void _InsertMoreDiv(string title)
        {
            this.BeginUpdate();
            this.BeginContentChangeLog();
            if (this.myContent.HasSelected())
            {
                this.myContent.DeleteSeleciton();
            }
            else if (!this.myOwnerControl.InsertMode)
            {
                this.myContent.DeleteCurrentElement();
            }
            ZYTextDiv newElement = new ZYTextDiv();
            newElement.timeTitle = "Y";
            newElement.Name = "";
            //newElement.FontSize = 14;
            newElement.CanDelete = true;
            newElement.Title = title;
            this.myContent.AutoClearSelection = true;
            //if (!(this.myContent.PreElement is ZYTextParagraph))
            //{
            //    this.myContent.InsertElement(new ZYTextParagraph());
            //}
            this.myContent.InsertElement(newElement);
            this.EndContentChangeLog();
            this.EndUpdate();
        }

        /// <summary>
        /// 清除选中内容的样式
        /// </summary>
        public void _DeleteFormat()
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                bool flag = false;
                foreach (object obj2 in this.myContent.GetSelectElements())
                {
                    ZYTextChar ch = obj2 as ZYTextChar;
                    if (ch != null)
                    {
                        ch.Font = this.myView.DefaultFont;
                        ch.Sub = false;
                        ch.Sup = false;
                        ch.ForeColor = (Color)ZYAttribute.GetDefaultValue("forecolor");
                        flag = true;
                        ch.RefreshSize();
                    }
                    ZYTextInput select = obj2 as ZYTextInput;
                    if (select != null)
                    {
                        select.Text = select.Name;
                        select.RefreshSize();
                        flag = true;
                    }
                }
                this.myContentChangeLog.strUndoName = "清除样式";
                if (flag)
                {
                    this.RefreshLine();
                }
                this.EndContentChangeLog();
                this.EndUpdate();
                if (flag)
                {
                    this.Refresh();
                }
            }
        }

        /// <summary>
        /// 删除表格
        /// </summary>
        public void _DeleteTable()
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                this.myContent.AutoClearSelection = true;
                ZYTextTable inTable = this.GetInTable(this.myContent.CurrentElement);
                if (inTable != null)
                {
                    inTable.Parent.ChildElements.Remove(inTable);
                    this.ContentChanged();
                }
                this.myContentChangeLog.strUndoName = "删除表格";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 删除表格
        /// </summary>
        public void _VibleTable()
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                this.myContent.AutoClearSelection = true;
                ZYTextTable inTable = this.GetInTable(this.myContent.CurrentElement);
                if (inTable != null)
                {
                    foreach (ZYTextTableRow var in inTable.Rows)
                    {
                        foreach (ZYTextTableCell var2 in var.Cells)
                        {
                            var2.border = var2.border == true ? false : true;
                        }
                    }
                }
                this.myContentChangeLog.strUndoName = "隐藏表格边框";
                this.EndContentChangeLog();
                this.EndUpdate();
                this.ContentChanged();
            }
        }


        /// <summary>
        /// 删除表格
        /// </summary>
        /// <param name="table"></param>
        public void _DeleteTable(ZYTextTable table)
        {
            if (table != null)
            {
                table.Parent.ChildElements.Remove(table);
                this.ContentChanged();
            }
        }

        /// <summary>
        /// 删除表格列
        /// </summary>
        public void _DeleteTableCol()
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                this.myContent.AutoClearSelection = true;
                ZYTextTableCell inTableCell = this.GetInTableCell(this.myContent.CurrentElement);
                if (inTableCell != null)
                {
                    if (inTableCell.OwnerTable.ColCount == 1)
                    {
                        this._DeleteTable(inTableCell.OwnerTable);
                    }
                    else
                    {
                        inTableCell.OwnerTable.RemoveCol(inTableCell);
                        this.ContentChanged();
                    }
                }
                this.myContentChangeLog.strUndoName = "删除表格列";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 删除表格行
        /// </summary>
        public void _DeleteTableRow()
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                this.myContent.AutoClearSelection = true;
                ZYTextTableRow inTableRow = this.GetInTableRow(this.myContent.CurrentElement);
                if (inTableRow != null)
                {
                    if (inTableRow.OwnerTable.RowCount == 1)
                    {
                        this._DeleteTable(inTableRow.OwnerTable);
                    }
                    else
                    {
                        inTableRow.OwnerTable.RemoveRow(inTableRow);
                        this.ContentChanged();
                    }
                }
                this.myContentChangeLog.strUndoName = "删除表格行";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="strFind"></param>
        /// 
        public void _Find(string strFind)
        {
            this.myContent.FindText(strFind);
        }

        public void _Find(string strFind, int selectStart)
        {
            this.myContent.FindText(strFind, selectStart);
        }

        /// <summary>
        /// 插入字符
        /// </summary>
        /// <param name="vChar"></param>
        /// <returns></returns>        

        public ZYTextElement _InsertChar(char vChar)
        {
            ZYTextElement element = null;
            if (this.Locked)
            {
                return null;
            }
            bool b = false;
            this.BeginUpdate();
            this.BeginContentChangeLog();
            if (this.myContent.HasSelected())
            {
                this.myContent.DeleteSeleciton();
            }
            else if (!this.myOwnerControl.InsertMode && (vChar != '\r'))
            {
                this.myContent.DeleteCurrentElement();
            }
            if (vChar == '\r')
            {
                string currentLineHeadBlank = this.myContent.GetCurrentLineHeadBlank();
                if (this.myOwnerControl.HasShiftPressing())
                {
                    ZYTextLineEnd newElement = new ZYTextLineEnd();
                    newElement.OwnerDocument = this;
                    this.myContent.InsertElement(newElement);
                    this.myContentChangeLog.strUndoName = "输入软回车";
                    element = newElement;
                }
                else
                {
                    ZYTextParagraph paragraph = new ZYTextParagraph();
                    paragraph.OwnerDocument = this;
                    ZYTextParagraph ownerParagraph = this.GetOwnerParagraph();
                    if (ownerParagraph != null)
                    {
                        paragraph.Align = ownerParagraph.Align;
                    }
                    this.myContent.InsertElement(paragraph);
                    this.myContentChangeLog.strUndoName = "输入硬回车";
                    element = paragraph;
                }
                //去掉多余的空格
                if ((currentLineHeadBlank.Trim() != null) && (currentLineHeadBlank.Trim().Length > 0))
                {
                    this.myContent.InsertString(currentLineHeadBlank);
                }
            }
            else
            {
                ZYTextTableCell inTableCell = this.GetInTableCell(this.myContent.CurrentElement);
                if ((vChar == '\t') && (inTableCell != null))
                {
                    ZYTextTableCell nextCell = this.GetInTable(this.myContent.CurrentElement).GetNextCell(inTableCell);
                    if (nextCell != null)
                    {
                        ZYTextParagraph firstParagraph = nextCell.GetFirstParagraph();
                        if (firstParagraph != null)
                        {
                            this.myContent.AutoClearSelection = true;
                            this.myContent.MoveTo(firstParagraph.RealLeft, firstParagraph.RealTop);
                            b = true;
                        }
                    }
                }
                else
                {
                    this.myContent.AutoClearSelection = true;
                    element = this.myContent.InsertChar(vChar);
                    if (element != null)
                    {
                        element.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);//511
                        this.myContentChangeLog.strUndoName = "输入字符 " + vChar;
                    }
                }
            }
            this.EndContentChangeLog();
            this.EndUpdate();
            this.ContentChanged();
            if (!b)
                this.Content.MoveSelectStart((int)(this.Content.intSelectStart + 1));
            return element;
        }

        /// <summary>
        /// 插入文本块
        /// </summary>
        /// <param name="strName"></param>
        public void _InsertDiv(string strName)
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                ZYTextDiv newElement = new ZYTextDiv();
                //if (this.Content.CurrentElement.Parent.Parent!=null)
                //{
                //    newElement.MarginLeft = 10;
                //}
                newElement.Name = strName;
                this.myContent.AutoClearSelection = true;
                if (!(this.myContent.PreElement is ZYTextParagraph))
                {
                    this.myContent.InsertElement(new ZYTextParagraph());
                }
                this.myContent.InsertElement(newElement);
                this.myContentChangeLog.strUndoName = "插入文本层";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        public void _insertSplit()
        {
            if (!this.Locked)
            {
                this.BeginContentChangeLog();
                this.BeginUpdate();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }

                ZYTextSplit split = new ZYTextSplit();
                split.OwnerDocument = this;
                this.myContent.InsertElement(split);
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(split);
                this.myContentChangeLog.strUndoName = "插入分割符";
                this.EndUpdate();
                this.EndContentChangeLog();
            }


        }

        /***
         * 向下插入文本块
         */
        public void _InsertDivDown(ZYTextDiv div, int type)
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                ZYTextDiv newElement = new ZYTextDiv();
                newElement.Name = " ";
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(newElement, div, type);
                this.myContentChangeLog.strUndoName = "插入文本层";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }


        bool[] updateDiagnose = new bool[] { false, false, false, false, false, false, false, false };

        private bool canOkDiagnose = false;

        public bool isRyText
        {
            get
            {
                return (this.Us.TextKind_id == 119
                    || this.Us.TextKind_id == 120
                    || this.Us.TextKind_id == 121
                    || this.Us.TextKind_id == 122);
            }
        }

        /// <summary>
        /// 刷新诊断列表
        /// </summary>
        //public void RefreshDiagnose(string _title, List<Diagnose_item> _diagnoseList, string ids)
        //{
        //    ArrayList arr = new ArrayList();
        //    if (_title.Contains("修正") || _title.Contains("补充"))
        //    {
        //        canOkDiagnose = true;
        //    }
        //    DiagnoseDiv(this.myDocumentElement, arr);
        //    //找到含标题的DIV并插入数据
        //    foreach (ZYTextElement element in arr)
        //    {
        //        if (element is ZYTextDiv)
        //        {
        //            ZYTextDiv ztd = (ZYTextDiv)element;
        //            if (ztd.Title.Contains(_title)
        //                || ((ztd.Title == "诊断:" || ztd.Title == "诊断：" || ztd.Title.Contains("病因诊断")) && _title == "目前诊断")
        //                || (_title == "转出诊断" && ztd.Title.Contains("转出时诊断"))
        //                || (_title == "转入诊断" && ztd.Title.Contains("转入时诊断")))
        //            {
        //                InsertDiaonose(_diagnoseList, (ZYTextDiv)element, ids);
        //            }
        //        }
        //        else if (element is ZYTextInput)
        //        {
        //            ZYTextInput input = (ZYTextInput)element;
        //            if (input.Name == _title.Trim())
        //            {
        //                InsertDiaonose(_diagnoseList, input);
        //            }
        //        }
        //    }
        //    this.ContentChanged();
        //    this.canOkDiagnose = false;
        //}

        public void RefreshDiagnose(string _title, List<Diagnose_item> _diagnoseList, string ids)
        {
            ArrayList arr = new ArrayList();
            DiagnoseDiv(this.myDocumentElement, arr);
            if (_title.Contains("修订") || _title.Contains("修正") || _title.Contains("补充") || _title.Contains("确定"))
            {
                canOkDiagnose = true;
            }

            if (_title.Contains("初步诊断") || _title.Contains("死亡诊断") || _title.Contains("入院诊断") || _title.Contains("出院诊断"))
            {
                if (arr != null && arr.Count > 0)
                {
                    foreach (ZYTextElement element in arr)
                    {
                        if (element is ZYTextDiv)
                        {
                            ZYTextDiv ztd = (ZYTextDiv)element;
                            if (ztd.Title.Contains("补充诊断") || ztd.Title.Contains("修订诊断") || ztd.Title.Contains("修正诊断") || ztd.Title.Contains("确定诊断"))
                            {
                                canOkDiagnose = true;
                                break;
                            }
                        }
                    }
                }
            }
            //找到含标题的DIV并插入数据
            foreach (ZYTextElement element in arr)
            {
                if (element is ZYTextDiv)
                {
                    ZYTextDiv ztd = (ZYTextDiv)element;
                    if (ztd.Title.Contains(_title)
                        || ((ztd.Title == "诊断:" || ztd.Title == "诊断：" || ztd.Title.Contains("病因诊断")) && _title == "目前诊断")
                        || (_title == "转出诊断" && ztd.Title.Contains("转出时诊断"))
                        || (_title == "转入诊断" && ztd.Title.Contains("转入时诊断")))
                    {
                        InsertDiaonose(_diagnoseList, (ZYTextDiv)element, ids);
                    }
                }
                else if (element is ZYTextInput)
                {
                    ZYTextInput input = (ZYTextInput)element;
                    if (input.Name == _title.Trim())
                    {
                        InsertDiaonose(_diagnoseList, input);
                    }
                }
            }
            this.ContentChanged();
            this.canOkDiagnose = false;
        }

        public bool IshaveDiagnoseDiv(string _title)
        {
            ArrayList arr = new ArrayList();
            DiagnoseDiv(this.myDocumentElement, arr);
            if (arr != null && arr.Count > 0)
            {
                foreach (ZYTextElement element in arr)
                {
                    if (element is ZYTextDiv)
                    {
                        ZYTextDiv ztd = (ZYTextDiv)element;
                        if (ztd.Title.Contains(_title)
                            || ((ztd.Title == "诊断:" || ztd.Title == "诊断：" || ztd.Title.Contains("病因诊断")) && _title == "目前诊断")
                            || (_title == "转出诊断" && ztd.Title.Contains("转出时诊断"))
                            || (_title == "转入诊断" && ztd.Title.Contains("转入时诊断")))
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        public void ExcuteDiagnoseSql()
        {
            if (sqlDiagnoseList != null && sqlDiagnoseList.Count > 0)
            {
                List<string> diagnoseList = new List<string>();
                foreach (string diagnoseKey in sqlDiagnoseList.Keys)
                {
                    foreach (string item in sqlDiagnoseList[diagnoseKey])
                    {
                        if (item.Contains("doc_id"))
                        {
                            string newSql = string.Format(item, this.Us.Tid);
                            diagnoseList.Add(newSql);
                        }
                        else
                        {
                            diagnoseList.Add(item);
                        }
                    }
                }
                App.ExecuteBatch(diagnoseList.ToArray());
                sqlDiagnoseList.Clear();
                diagnoseList.Clear();
            }
        }

        /***
         * 获取诊断层集合
         */
        public void DiagnoseDiv(ZYTextContainer container, ArrayList Arr)
        {
            foreach (ZYTextElement element in container.ChildElements)
            {
                if (element is ZYTextContainer)
                {
                    DiagnoseDiv((ZYTextContainer)element, Arr);
                }

                if (element is ZYTextInput && !element.Deleteted)
                {
                    if (((ZYTextInput)element).Name.Contains("诊断"))
                    {
                        Arr.Add(element);
                    }
                }
                if (element is ZYTextDiv && !element.Deleteted)
                {
                    Arr.Add(element);
                }
            }
        }

        private string isTextSuperiorSignature = "";
        /// <summary>
        /// 是否需要上级医生签名
        /// </summary>
        public string TextSuperiorSignature
        {
            get { return isTextSuperiorSignature; }
            set { this.isTextSuperiorSignature = value; }
        }

        private string _haveTubebedSign = "";
        /// <summary>
        /// 管床医生是否审签
        /// </summary>
        public string HaveTubebedSign
        {
            get { return _haveTubebedSign; }
            set { _haveTubebedSign = value; }
        }

        private string _haveSuperiorSignature = "";
        /// <summary>
        /// 是否已经有过上级医生签名
        /// </summary>
        public string HaveSuperiorSignature
        {
            get { return _haveSuperiorSignature; }
            set { _haveSuperiorSignature = value; }
        }

        /// <summary>
        /// 插入诊断
        /// </summary>
        /// <param name="ztd"></param>
        /// <param name="dr"></param>
        //private void InsertDiaonose(List<Diagnose_item> diagnoseStrs, ZYTextDiv ztd, string ids)
        //{
        //    if (!canOkDiagnose)
        //        ztd.ChildElements.Clear();
        //    ZYTextTable _parentTable = this.GetInTable(ztd);
        //    if (diagnoseStrs.Count > 0)
        //    {
        //        int titleWidth = (int)(ztd.TitleSize().Width);
        //        ArrayList myList = GetDiagnosesToArr(diagnoseStrs, titleWidth);
        //        ArrayList list = new ArrayList();
        //        #region
        //        if (this.canOkDiagnose)
        //        {
        //            //新建
        //            if (ztd.ChildCount < 3)
        //            {
        //                ztd.ChildElements.Clear();
        //            }
        //            int ContainerCount = ztd.ChildCount;
        //            ZYTextInput lastSignInput = null;
        //            if (lastSignInput == null)
        //            {
        //                #region
        //                foreach (ZYTextElement element in myList)
        //                {
        //                    element.OwnerDocument = this;
        //                    element.Parent = ztd;
        //                    element.CreatorIndex = this.SaveLogs.CurrentIndex;
        //                    list.Add(element);
        //                }
        //                ZYTextInput OkSign = new ZYTextInput();
        //                OkSign.OwnerDocument = this;
        //                OkSign.Parent = ztd;
        //                OkSign.CanDelete = true;
        //                OkSign.ID = App.UserAccount.UserInfo.User_id;
        //                OkSign.Name = "补充修正医师签名";
        //                OkSign.Text = "        " + App.UserAccount.UserInfo.User_name;
        //                //foreach (char var in "          ".ToCharArray())
        //                //{
        //                //    ZYTextChar _char = this.CreateChar(var);
        //                //    _char.OwnerDocument = this;
        //                //    _char.Parent = ztd;
        //                //    list.Add(_char);
        //                //}
        //                list.Add(OkSign);
        //                ZYTextParagraph paragraph = new ZYTextParagraph();
        //                paragraph.OwnerDocument = this;
        //                paragraph.Parent = ztd;
        //                paragraph.LeftChars = titleWidth;
        //                paragraph.RefreshSize();
        //                list.Add(paragraph);
        //                ZYTextInput OkSignTime = new ZYTextInput();
        //                OkSignTime.OwnerDocument = this;
        //                OkSignTime.Parent = ztd;
        //                OkSignTime.Name = "医师签名时间";
        //                OkSignTime.Text = App.GetSystemTime().ToString("yyyy-MM-dd，HH:mm");
        //                //foreach (char var in "          ".ToCharArray())
        //                //{
        //                //    ZYTextChar _char = this.CreateChar(var);
        //                //    _char.OwnerDocument = this;
        //                //    _char.Parent = ztd;
        //                //    list.Add(_char);
        //                //}
        //                list.Add(OkSignTime);
        //                ZYTextParagraph paragraph2 = new ZYTextParagraph();
        //                paragraph2.OwnerDocument = this;
        //                paragraph2.Parent = ztd;
        //                paragraph2.LeftChars = titleWidth;
        //                paragraph2.RefreshSize();
        //                list.Add(paragraph2);
        //                ztd.ChildElements.AddRange(list);
        //                this.RefreshSize();
        //                #endregion
        //            }
        //        }
        //        else

        //        #endregion
        //        {
        //            foreach (ZYTextElement element in myList)
        //            {
        //                element.Parent = ztd;
        //                element.OwnerDocument = this;
        //                element.DeleterIndex = -1;
        //                element.CreatorIndex = this.SaveLogs.CurrentIndex;
        //                element.RefreshSize();
        //                list.Add(element);
        //            }
        //            ztd.Sign = ids;
        //            ztd.CanDelete = false;
        //            ztd.ChildElements.InsertRange(0, list);
        //            ztd.CanDelete = true;
        //        }
        //    }
        //    else
        //    {
        //        if (!canOkDiagnose)
        //        {
        //            RemoveDiagnose(ztd);
        //            ZYTextParagraph para = new ZYTextParagraph();
        //            para.OwnerDocument = this;
        //            para.Parent = ztd;
        //            ztd.ChildElements.Add(para);
        //            para.RefreshSize();
        //        }
        //    }
        //    if (_parentTable != null)
        //    {
        //        this.RefreshElements();
        //        this.RefreshSize();
        //    }
        //    this.RefreshSize();
        //}

        /// <summary>
        /// 插入诊断
        /// </summary>
        /// <param name="ztd"></param>
        /// <param name="dr"></param>
        private void InsertDiaonose(List<Diagnose_item> diagnoseStrs, ZYTextDiv ztd, string ids)
        {
            if (!canOkDiagnose || ztd.Title.Contains("确定") || ztd.Title.Contains("初步") || ztd.Title.Contains("入院") || ztd.Title.Contains("死亡"))
            {
                ztd.ChildElements.Clear();
            }
            ZYTextTable _parentTable = this.GetInTable(ztd);
            if (diagnoseStrs.Count > 0)
            {
                int titleWidth = (int)(ztd.TitleSize().Width);
                ArrayList myList = GetDiagnosesToArr(diagnoseStrs, titleWidth);
                ArrayList list = new ArrayList();
                #region
                if (this.canOkDiagnose)
                {
                    //新建
                    if (ztd.ChildCount < 3)
                    {
                        ztd.ChildElements.Clear();
                    }
                    int ContainerCount = ztd.ChildCount;
                    ZYTextInput lastSignInput = null;
                    if (lastSignInput == null)
                    {
                        #region
                        foreach (ZYTextElement element in myList)
                        {
                            element.OwnerDocument = this;
                            element.Parent = ztd;
                            element.CreatorIndex = this.SaveLogs.CurrentIndex;
                            list.Add(element);
                        }

                        string timeText = string.Empty;// ztd.Title.Contains("修订") ? "修订日期：" : ztd.Title.Contains("确定") ? "确诊日期：" : ztd.Title.Contains("初步") ? "诊断日期：" : ztd.Title.Contains("死亡") ? "死亡日期：" : "补充日期：";
                        string signText = string.Empty;// ztd.Title.Contains("修订") ? "修订医师：" : ztd.Title.Contains("确定") ? "确诊医师：" : (ztd.Title.Contains("初步") || ztd.Title.Contains("死亡")) ? "医师签名：" : "补充医师：";

                        ZYTextInput OkSignTime = new ZYTextInput();
                        OkSignTime.OwnerDocument = this;
                        OkSignTime.Parent = ztd;
                        OkSignTime.Name = "医师签名日期";
                        OkSignTime.Text = App.GetSystemTime().ToString("yyyy-MM-dd");

                        ZYTextParagraph paragraph2 = new ZYTextParagraph();
                        paragraph2.OwnerDocument = this;
                        paragraph2.Parent = ztd;

                        //paragraph2.Align = ParagraphAlignConst.Right;
                        paragraph2.LeftChars = titleWidth;
                        paragraph2.RefreshSize();

                        ZYTextInput OkSign2 = new ZYTextInput();
                        OkSign2.OwnerDocument = this;
                        OkSign2.Parent = ztd;
                        OkSign2.CanDelete = true;
                        OkSign2.Name = "补充修正上级医师签名";
                        ZYTextInput OkSign = new ZYTextInput();
                        OkSign.OwnerDocument = this;
                        OkSign.Parent = ztd;
                        OkSign.CanDelete = true;
                        OkSign.ID = App.UserAccount.UserInfo.User_id;
                        OkSign.Name = "补充修正医师签名";
                        OkSign.Text = App.UserAccount.UserInfo.U_tech_post_name + "：      " + App.UserAccount.UserInfo.User_name;
                        list.Add(OkSign2);
                        list.Add(OkSign);
                        ZYTextParagraph paragraph = new ZYTextParagraph();
                        paragraph.OwnerDocument = this;

                        paragraph.LeftChars = titleWidth;
                        //paragraph.Align = ParagraphAlignConst.Right;
                        paragraph.Parent = ztd;
                        paragraph.RefreshSize();
                        list.Add(paragraph);
                        list.Add(OkSignTime);
                        list.Add(paragraph2);
                        ztd.ChildElements.AddRange(list);
                        this.RefreshSize();
                        #endregion
                    }
                }
                else

                #endregion
                {
                    foreach (ZYTextElement element in myList)
                    {
                        element.Parent = ztd;
                        element.OwnerDocument = this;
                        element.DeleterIndex = -1;
                        element.CreatorIndex = this.SaveLogs.CurrentIndex;
                        element.RefreshSize();
                        list.Add(element);
                    }
                    ztd.Sign = ids;
                    ztd.CanDelete = false;
                    ztd.ChildElements.InsertRange(0, list);
                    ztd.CanDelete = true;
                }
            }
            else
            {
                if (!canOkDiagnose)
                {
                    RemoveDiagnose(ztd);
                    ZYTextParagraph para = new ZYTextParagraph();
                    para.OwnerDocument = this;
                    para.Parent = ztd;
                    ztd.ChildElements.Add(para);
                    para.RefreshSize();
                }
            }
            if (_parentTable != null)
            {
                this.RefreshElements();
                this.RefreshSize();
            }
            this.RefreshSize();
        }

        //根据签名删除
        public bool RemoveOkSignToId(ZYTextInput _signInput)
        {
            try
            {
                ArrayList elementToList = GetOkSignList(_signInput, _signInput.Parent);
                ZYTextContainer InputContainer = _signInput.Parent;
                InputContainer.RemoveChildRange(elementToList);
                if (InputContainer.ChildCount == 0)
                {
                    ZYTextParagraph para = new ZYTextParagraph();
                    para.OwnerDocument = this;
                    para.Parent = InputContainer;
                    para.RefreshSize();
                    InputContainer.ChildElements.Add(para);
                }
            }
            catch
            {

                return false;
            }
            return true;
        }

        //获取最后一个转科医师签名获取最后一个确定诊断
        private static ArrayList GetOkSignList(ZYTextInput _input, ZYTextContainer _container)
        {
            int inputIndex = _container.IndexOf(_input);
            int containerElementCount = _container.ChildCount;
            ArrayList okDiagnoselist = new ArrayList(); //签名中间的
            try
            {
                int isHaveParagraph = 0;
                for (int i = inputIndex; i < containerElementCount; i++)
                {
                    ZYTextElement element = (ZYTextElement)_container.ChildElements[i];
                    if (element is ZYTextParagraph)
                    {
                        ZYTextParagraph zp = (ZYTextParagraph)element;
                        if (zp.Align == ParagraphAlignConst.Left)
                        {
                            if (isHaveParagraph == 2)
                            {
                                okDiagnoselist.Add(element);
                                break;
                            }
                            isHaveParagraph = 2;
                        }
                    }
                    okDiagnoselist.Add(element);
                }

                for (int i = inputIndex + 1; i >= 0; i--)
                {
                    ZYTextElement element = (ZYTextElement)_container.ChildElements[i];
                    ZYTextElement element2 = null;
                    int x = i - 1;
                    if (x >= 0)
                        element2 = (ZYTextElement)_container.ChildElements[i - 1];
                    if (element is ZYTextParagraph && i < inputIndex && element2 is ZYTextInput)
                    {
                        ZYTextParagraph zp = (ZYTextParagraph)element;
                        if (zp.Align == ParagraphAlignConst.Left)
                        {
                            break;
                        }
                    }
                    okDiagnoselist.Add(element);
                }
            }
            catch
            {
                return null;
            }
            return okDiagnoselist;
        }

        /// <summary>
        /// 转换成元素
        /// </summary>
        /// <param name="diagnoseStrs"></param>
        /// <param name="titleWhiteSpace"></param>
        /// <returns></returns>
        private ArrayList GetDiagnosesToArr(List<Diagnose_item> diagnoseStrs, int titleWhiteSpace)
        {
            //string text1 = "<span>{0}</span>";
            //string text2 = "<p leftchars = '{0}' />";
            //StringBuilder strb = new StringBuilder();
            //strb.Append("<emrtextdocument2005>");
            //int diagnoseLength = diagnoseStrs.Count;
            //int currentDiagnose = 0;
            //for (int i = 0; i < diagnoseLength; i++)
            //{

            //    Diagnose_item item = diagnoseStrs[i];
            //    if (item.Lever == 0)
            //        currentDiagnose++;
            //    string diagNose = item.DiagnoseName.Trim();
            //    if (item.Lever == 0)
            //    {
            //        diagNose = currentDiagnose.ToString() + "." + diagNose;
            //    }
            //    strb.Append(string.Format(text1, diagNose));
            //    strb.Append(string.Format(text2, ((item.Lever * (item.Lever == 1 ? 36 : 34)) + (item.Lever > 0 ? 12 : 0) + titleWhiteSpace)));
            //}
            //XmlDocument document = new XmlDocument();
            //document.PreserveWhitespace = true;
            //strb.Append("</emrtextdocument2005>");
            //ArrayList myList = new ArrayList();
            //document.LoadXml(strb.ToString());
            //this.LoadElementsToList(document.DocumentElement, myList);
            //foreach (ZYTextElement element in myList)
            //{
            //    if (element is ZYTextChar)
            //    {
            //        ZYTextChar charInsert = (ZYTextChar)element;
            //        if (isEnglishNum(charInsert.Char))
            //        {
            //            charInsert.Font = this.myView.DefaultEnglishNumFont;
            //        }
            //        else
            //        {
            //            charInsert.Font = this.myView.DefaultFont;
            //        }
            //    }
            //}
            string text1 = "<span>{0}</span>";
            string text2 = "<p leftchars = '{0}' />";
            StringBuilder strb = new StringBuilder();
            SizeF ef = this.View.Graph.MeasureString("一", this.myView.DefaultFont, 1000, StringFormat.GenericTypographic);

            strb.Append("<emrtextdocument2005>");
            int twoCharSize = 0;
            int diagnoseLength = diagnoseStrs.Count;
            int x = 1;
            bool haveZX = false;
            for (int i = 0; i < diagnoseLength; i++)
            {
                Diagnose_item item = diagnoseStrs[i];
                if (item.ZyStart)
                {
                    twoCharSize = Convert.ToInt32(ef.Width * 4.5);
                    haveZX = true;
                    x++;
                }

                string diagNose = item.DiagnoseName.Trim();
                strb.Append(string.Format(text1, diagNose));

                int marginLeftWidth = titleWhiteSpace; //(item.Lever * Convert.ToInt32(ef.Width) * 2 + ((x == 2 && item.Lever == 0) ? Convert.ToInt32(ef.Width) : 0) + titleWhiteSpace + (item.ZyStart ? 0 : twoCharSize));
                if (haveZX)
                {
                    if (!item.ZyStart)
                        marginLeftWidth += twoCharSize;
                }
                if (item.Lever > 0)
                {
                    marginLeftWidth += (item.Lever * Convert.ToInt32(ef.Width) * 2);
                }
                strb.Append(string.Format(text2, marginLeftWidth));
            }
            XmlDocument document = new XmlDocument();
            document.PreserveWhitespace = true;
            strb.Append("</emrtextdocument2005>");
            ArrayList myList = new ArrayList();
            document.LoadXml(strb.ToString());
            this.LoadElementsToList(document.DocumentElement, myList);
            return myList;
        }

        /// <summary>
        /// 移除诊断
        /// </summary>
        /// <param name="title">诊断名称</param>
        public void RemoveDiagnoseForTitle(string title, ZYTextInput _input)
        {
            if (this.isRyText)
            {
                ArrayList list = new ArrayList();
                DiagnoseDiv(this.myDocumentElement, list);
                if (list != null && list.Count > 0)
                {
                    foreach (object element in list)
                    {
                        if (element is ZYTextDiv)
                        {
                            ZYTextDiv ztd = (ZYTextDiv)element;
                            if (ztd.Title.Contains(title))
                            {
                                RemoveDiagnose(ztd);
                                break;
                            }
                        }
                    }
                }
            }
            _input.ID = "";
            _input.Text = "";

            SaveTrue = true;
            ContentChanged();
        }

        public static void RemoveDiagnose(ZYTextDiv ztd)
        {
            ztd.ClearChild();
            ZYTextDiv zt = (ztd.Parent is ZYTextDiv && ztd.Parent.Parent != null) ? (ZYTextDiv)ztd.Parent : null;
            if (zt != null)
            {
                //foreach (ZYTextElement element in zt.ChildElements)
                //{
                //    if (element is ZYTextInput)
                //    {
                //        ZYTextInput input = (ZYTextInput)element;
                //        if (input.Name != null && (input.Name == "上级医师签名" || input.Name == "管床医师签名" || input.Name == "普通医师签名" || input.Name == "普通医师日期" || input.Name == "上级医师日期"))
                //        {
                //            input.Text = "";
                //            input.ID = "";
                //        }
                //    }
                //}
            }
        }

        /// <summary>
        /// 插入诊断
        /// </summary>
        /// <param name="ztd"></param>
        /// <param name="dr"></param>
        private void InsertDiaonose(List<Diagnose_item> diagnoseStrs, ZYTextInput input)
        {
            input.Text = "";
            int diagnoseLength = diagnoseStrs.Count;
            if (diagnoseLength > 0)
            {
                Dictionary<int, int> lever = new Dictionary<int, int>();
                StringBuilder strb = new StringBuilder();
                for (int i = 0; i < diagnoseLength; i++)
                {
                    Diagnose_item iterm = diagnoseStrs[i];
                    //strb.Append(iterm.Index.ToString());
                    //if (iterm.Lever > 0)
                    //    strb.Append(")");
                    //else
                    //    strb.Append("、");
                    strb.Append(iterm.DiagnoseName);
                    if (i == diagnoseLength - 1)
                        strb.Append("。");
                    else
                        strb.Append("；");
                }
                input.Text = strb.ToString();
            }
            else
            {
                input.Text = "";
            }
        }

        public void InsertDiaonose1(ZYTextDiv ztd, DataRow[] dr)
        {
            ztd.ClearChild();
            for (int i = 0; i < dr.Length; i++)
            {
                string diagnoseName = (i + 1).ToString() + "、" + dr[i]["diagnose_name"].ToString();
                foreach (char ch in diagnoseName.ToCharArray())
                {
                    ZYTextChar ztc = CreateChar(ch);
                    ztc.OwnerDocument = this;
                    ztc.Parent = ztd;
                    ztd.ChildElements.Add(ztc);
                }
                DataTable dt2 = App.GetDataSet(string.Format("select trend_diagnose_name from t_trend_diagnose where diagnoseitem_id = '{0}'", dr[i]["id"].ToString())).Tables[0];
                if (dt2.Rows.Count > 0)
                {
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        ZYTextParagraph zp2 = new ZYTextParagraph();
                        zp2.OwnerDocument = this;
                        zp2.Parent = ztd;
                        ztd.ChildElements.Add(zp2);
                        string diagnoseName2 = "  (" + (j + 1).ToString() + ")、" + dt2.Rows[j][0].ToString();
                        foreach (char ch2 in diagnoseName2.ToCharArray())
                        {
                            ZYTextChar zyc2 = CreateChar(ch2);
                            zyc2.Parent = ztd;
                            zyc2.OwnerDocument = this;
                            ztd.ChildElements.Add(zyc2);
                        }
                    }
                }
                ZYTextParagraph zp = new ZYTextParagraph();
                zp.OwnerDocument = this;
                zp.Parent = ztd;
                ztd.ChildElements.Add(zp);
            }
        }

        /// <summary>
        /// 插入文档
        /// </summary>
        /// <param name="strID"></param>
        /// <returns></returns>
        public bool _InsertDocument(string strID)
        {
            ET_Document myRecord = new ET_Document();
            ZYTextElement currentElement = this.myContent.CurrentElement;
            if (((currentElement != null) && myRecord.SetKeyWord(strID)) && this.myDataSource.DBConn.ReadOneRecord(myRecord))
            {
                bool flag = false;
                try
                {
                    XmlElement documentElement = myRecord.GetDataXML().DocumentElement;
                    XmlElement element3 = XMLCommon.GetElementByName(documentElement, this.myScript.GetXMLName(), false);
                    if (element3 != null)
                    {
                        this.myScript.AppendSourceCode(element3.InnerText);
                    }
                    ZYTextContainer container = this.CreateElementByXML(GetBodyElement(documentElement)) as ZYTextContainer;
                    if (container == null)
                    {
                        goto Label_011F;
                    }
                    container.ClearSaveLog();
                    ArrayList myList = new ArrayList();
                    myList.AddRange(container.ChildElements);
                    for (int i = 0; i < container.ChildElements.Count; i++)
                    {
                        ZYTextSelect select = container.ChildElements[i] as ZYTextSelect;
                        if (select != null)
                        {
                            select.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);
                            if ((select.Sign == null) || (select.Sign.Equals("") || (select.Sign.Equals("0"))))
                                select.Sign = "值:" + select.DisplayName + ",创建时间:" + (DateTime.Now).ToString("yyyy年MM月dd日 HH:mm") + ",IP:" + this.GetUserIP();
                        }

                    }

                    if ((myList.Count > 0) && (myList[myList.Count - 1] is ZYTextParagraph))
                    {
                        myList.RemoveAt(myList.Count - 1);
                    }
                    this.BeginContentChangeLog();
                    currentElement.Parent.InsertRangeBefore(myList, currentElement);
                    this.EndContentChangeLog();
                    this.RefreshSize();
                    this.RefreshElements();
                    this.RefreshLine();
                    this.UpdateView();
                    this.myContent.CurrentElement = currentElement;
                    flag = true;
                }
                catch
                {
                }
                return flag;
            }
        Label_011F:
            return false;
        }

        bool isAutograph = false;
        public bool AutoGraph
        {
            set
            {
                isAutograph = value;
            }
        }

        bool isNeedTimeTitle = false;
        public bool NeedTimeTitle
        {
            set
            {
                isNeedTimeTitle = true;
            }
        }

        /***
               * 插入签名 病程记录
               */
        public bool _InsertSignature()
        {
            if (!this.Locked)
            {
                ArrayList list = GetQmList("普通医师签名");
                if (list != null)
                {
                    ZYTextInput input = (ZYTextInput)list[0];
                    if (input.ID == App.UserAccount.UserInfo.User_id) //如果签名ID = 登录ID true
                    {
                        return true;
                    }

                    string hightId = App.GetTheHighLevelUserId(input.ID, App.UserAccount.UserInfo.User_id);
                    if (hightId == App.UserAccount.UserInfo.User_id)
                    {
                        ZYTextInput _input = new ZYTextInput();
                        _input.OwnerDocument = this;
                        _input.Name = "普通医师签名";
                        //医师姓名
                        _input.Text = "        " + App.UserAccount.UserInfo.User_name;
                        //医师ID
                        _input.ID = App.UserAccount.UserInfo.User_id;
                        _input.CanDelete = true;
                        _InsertSignature(_input, input);
                        return true;
                    }
                    else
                    {
                        App.Msg("您登录账号的级别不够！");
                        return false;
                    }
                }
                if (App.UserAccount.UserInfo != null)
                {
                    ZYTextInput input = null;
                    ArrayList arrlist = new ArrayList();
                    DiagnoseDiv(this.myDocumentElement, arrlist);
                    if (arrlist.Count > 0)
                    {
                        foreach (ZYTextElement element1 in arrlist)
                        {
                            if (element1 is ZYTextInput)
                            {
                                ZYTextInput _input = (ZYTextInput)element1;
                                if (_input.Name == "普通医师签名")
                                {
                                    input = _input;
                                    if (_input.Text == "")
                                    {
                                        //医师姓名
                                        input.Text = "        " + App.UserAccount.UserInfo.User_name;
                                        //医师ID
                                        input.ID = App.UserAccount.UserInfo.User_id;
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    if (list == null)
                    {
                        input = new ZYTextInput();
                        input.OwnerDocument = this;
                        input.Name = "普通医师签名";
                        //医师姓名
                        input.Text = "        " + App.UserAccount.UserInfo.User_name;
                        //医师ID
                        input.ID = App.UserAccount.UserInfo.User_id;
                        input.CanDelete = true;
                        ZYTextElement element = (ZYTextElement)this.Elements[this.Elements.Count - 1];
                        ArrayList arr = new ArrayList();
                        if (element is ZYTextParagraph && element.Parent == this.myDocumentElement)
                        {
                            ZYTextParagraph ztp = (ZYTextParagraph)element;
                            if (ztp.OwnerLine.Elements.Count > 1)
                            {
                                ZYTextParagraph ztp2 = new ZYTextParagraph();
                                ztp2.OwnerDocument = this;
                                arr.Add(ztp2);
                            }
                            if (this.Us.TextKind_id == 1162 || this.Us.TextKind_id == 1161)
                            {
                                foreach (char var in "医师签名：".ToCharArray())
                                {
                                    ZYTextChar _char = this.CreateChar(var);
                                    _char.OwnerDocument = this;
                                    arr.Add(_char);
                                }
                            }
                            arr.Add(input);
                            ztp.RightAlign = true;
                            if (this.Us.TextKind_id == 1162 || this.Us.TextKind_id == 1201 || this.Us.TextKind_id == 120 || this.Us.TextKind_id == 121 || this.Us.TextKind_id == 1162 || this.Us.TextKind_id == 1161)
                            {
                                ZYTextParagraph ztp2 = new ZYTextParagraph();
                                ztp2.OwnerDocument = this;
                                ztp2.RightAlign = true;
                                arr.Add(ztp2);
                                ZYTextInput timeInput = new ZYTextInput();
                                timeInput.OwnerDocument = this;
                                timeInput.Name = "文书时间";
                                timeInput.CanDelete = true;
                                timeInput.Text = App.GetSystemTime().ToString("yyyy-MM-dd，HH:mm");
                                arr.Add(timeInput);
                            }
                            this.myDocumentElement.InsertRangeBefore(arr, ztp);
                        }
                    }
                }
                this.ContentChanged();
            }
            return true;
        }

        public void _InsertSignature(ZYTextInput _qm, ZYTextInput _input)
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                this.myContent.AutoClearSelection = true;
                this.myDocumentElement.InsertBefore(_qm, _input);
                this.myContentChangeLog.strUndoName = "插入签名";
                this.EndContentChangeLog();
                this.EndUpdate();
                this.ContentChanged();
            }
        }

        /***
         * 获取签名元素
         */
        public List<ZYTextInput> GetQmList()
        {
            List<ZYTextInput> list = new List<ZYTextInput>();
            foreach (ZYTextElement _element in this.Elements)
            {
                if (_element is ZYTextInput)
                {
                    ZYTextInput _input = (ZYTextInput)_element;
                    if (_input.Name == "普通医师签名"
                        || _input.Name == "上级医师职称"
                        || _input.Name == "上级医师签名"
                        || _input.Name == "管床医师签名"
                        || _input.Name == "普通护士签名")
                    {
                        list.Add(_input);
                    }
                }
            }
            if (list.Count > 0)
                return list;
            return null;
        }

        /***
       * 获取签名元素
       */
        public ArrayList GetQmList(string qmName)
        {
            ArrayList list = new ArrayList();
            foreach (ZYTextElement _element in this.Elements)
            {
                if (_element is ZYTextInput)
                {
                    ZYTextInput _input = (ZYTextInput)_element;
                    if (_input.Name == qmName)
                    {
                        list.Add(_input);
                    }
                }
            }
            if (list.Count > 0)
                return list;
            return null;
        }

        public void _InsertString(string _text)
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertString(_text);
                this.myContentChangeLog.strUndoName = "插入字符串";
                this.EndContentChangeLog();
                this.EndUpdate();
                this.ContentChanged();
            }
        }

        /// <summary>
        /// 插入元素
        /// </summary>
        public void _InsertMedia(string value)
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                this.myContent.AutoClearSelection = true;
                ZYTextMedia newElement = new ZYTextMedia();
                newElement.Value = value;
                newElement.OwnerDocument = this;
                newElement.UpdateText();
                this.myContent.InsertElement(newElement);
                this.myContent.MoveSelectStart(this.myContent.intSelectStart + 1);
                this.myContentChangeLog.strUndoName = "插入签名";
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 插入复选框
        /// </summary>
        /// <param name="checkText"></param>
        public void _InsertCheckBox(string checkText)
        {
            if (!this.Locked)
            {
                this.BeginContentChangeLog();
                this.BeginUpdate();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }

                ZYTextCheckBox ztt = new ZYTextCheckBox();
                ztt.OwnerDocument = this;
                ztt.check = "N";

                //ZYTextCheck zc = new ZYTextCheck();
                //zc.check = "N";


                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(ztt);
                this.myContentChangeLog.strUndoName = "插入复选框" + "N";
                this.EndUpdate();
                this.EndContentChangeLog();
            }
        }


        public bool _InsertDocument(string XmlElement, int xxx, ZYTextInput _input)
        {
            ET_Document myRecord = new ET_Document();
            ZYTextElement currentElement = this.myContent.CurrentElement;
            this.myContent.AutoClearSelection = true;
            if ((currentElement != null) && XmlElement != "")
            {
                bool flag = false;
                try
                {
                    XmlDocument xmltemp = new XmlDocument();
                    xmltemp.PreserveWhitespace = true;
                    xmltemp.LoadXml(XmlElement);
                    XmlElement documentElement = xmltemp.DocumentElement;
                    ZYTextContainer container = this.CreateElementByXML(GetBodyElement(documentElement)) as ZYTextContainer;
                    if (container == null)
                    {
                        goto Label_011F;
                    }
                    ArrayList myList = new ArrayList();
                    myList.AddRange(container.ChildElements);
                    for (int i = 0; i < container.ChildElements.Count; i++)
                    {
                        ZYTextSelect select = container.ChildElements[i] as ZYTextSelect;
                        if (select != null)
                        {
                            select.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);
                            //(新加的属性)*********************
                            if ((select.Sign == null) || (select.Sign.Equals("") || (select.Sign.Equals("0"))))
                                select.Sign = "值:" + select.DisplayName + ",创建时间:" + (DateTime.Now).ToString("yyyy年MM月dd日 HH:mm") + ",IP:" + this.GetUserIP();
                        }

                    }

                    if ((myList.Count > 0) && (myList[myList.Count - 1] is ZYTextParagraph))
                    {
                        myList.RemoveAt(myList.Count - 1);
                    }

                    this.BeginContentChangeLog();
                    _input.ClearChild();
                    _input.InsertRangeBefore(myList, (ZYTextElement)_input.ChildElements[0]);
                    this.myContentChangeLog.strUndoName = "插入复杂元素";
                    this.EndContentChangeLog();
                    this.UpdateView();
                    this.ContentChanged();
                    flag = true;
                }
                catch
                {
                }
                return flag;
            }
        Label_011F:
            return false;
        }

        public bool _InsertDocument(string XmlElement, int xx)
        {
            ET_Document myRecord = new ET_Document();
            ZYTextElement currentElement = this.myContent.CurrentElement;
            this.myContent.AutoClearSelection = true;
            if ((currentElement != null) && XmlElement != "")
            {
                bool flag = false;
                try
                {
                    XmlDocument xmltemp = new XmlDocument();
                    xmltemp.PreserveWhitespace = true;
                    xmltemp.LoadXml(XmlElement);
                    XmlElement documentElement = xmltemp.DocumentElement;
                    ZYTextContainer container = this.CreateElementByXML(GetBodyElement(documentElement)) as ZYTextContainer;
                    if (container == null)
                    {
                        goto Label_011F;
                    }
                    ArrayList myList = new ArrayList();
                    myList.AddRange(container.ChildElements);
                    if ((myList.Count > 0) && (myList[myList.Count - 1] is ZYTextParagraph))
                    {
                        myList.RemoveAt(myList.Count - 1);
                    }

                    this.BeginContentChangeLog();
                    this.myContent.InsertRangeElements(myList);
                    this.myContentChangeLog.strUndoName = "插入复杂元素";
                    this.EndContentChangeLog();
                    this.UpdateView();
                    this.ContentChanged();
                    flag = true;
                }
                catch
                {
                }
                return flag;
            }
        Label_011F:
            return false;
        }


        /// <summary>
        /// 插入元素
        /// </summary>
        /// <param name="NewElement"></param>
        public void _InsertElement(ZYTextElement NewElement)
        {
            if (!this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(NewElement);
                this.myContentChangeLog.strUndoName = "插入元素";
                this.myContent.MoveSelectStart((int)(this.myContent.SelectStart));
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 插入域
        /// </summary>
        /// <param name="strID"></param>
        /// <param name="strName"></param>
        /// <returns></returns>
        public ZYTextInput _InsertInput(string strID, string strName)
        {
            if (this.Locked)
            {
                return null;
            }
            this.BeginUpdate();
            this.BeginContentChangeLog();
            if (this.myContent.HasSelected())
            {
                this.myContent.DeleteSeleciton();
            }
            else if (!this.myOwnerControl.InsertMode)
            {
                this.myContent.DeleteCurrentElement();
            }
            ZYTextInput newElement = new ZYTextInput();
            if (strName == null)
            {
                strName = strID;
            }
            newElement.OwnerDocument = this;
            newElement.Name = strName;
            this.myContent.InsertElement(newElement);
            this.myContentChangeLog.strUndoName = "插入域 " + strName;
            this.EndContentChangeLog();
            this.EndUpdate();
            return newElement;
        }

        public void _InsertBorderInput()
        {
            if (this.Locked)
            {
                return;
            }
            this.BeginUpdate();
            this.BeginContentChangeLog();
            if (this.myContent.HasSelected())
            {
                this.myContent.DeleteSeleciton();
            }
            else if (!this.myOwnerControl.InsertMode)
            {
                this.myContent.DeleteCurrentElement();
            }
            ZYTextBorderInput newElement = new ZYTextBorderInput();
            newElement.OwnerDocument = this;
            this.myContent.InsertElement(newElement);
            this.myContentChangeLog.strUndoName = "插入边框文本域 ";
            this.EndContentChangeLog();
            this.EndUpdate();
        }

        /// <summary>
        /// 插入知识库
        /// </summary>
        /// <param name="OnlyTemplate"></param>
        /// <returns></returns>
        public int _InsertKB(bool OnlyTemplate)
        {
            if (this.Locked || !this.CheckKBLoaded())
            {
                return -1;
            }
            bool flag = false;
            bool flag2 = false;
            int num = -1;
            ArrayList myOutList = new ArrayList();
            string selectedText = this.myContent.GetSelectedText();
            if (StringCommon.isBlankString(selectedText))
            {
                selectedText = this.myContent.GetPreWord();
            }
            else
            {
                flag = true;
            }
            ZYKBBuffer.Instance.SearchTemplateOnly = OnlyTemplate;
            flag2 = ZYKBBuffer.Instance.GetKBListsByName(selectedText, myOutList, true);
            object obj2 = this.myOwnerControl.ShowKBPopupList(this.myContent.CurrentElement, myOutList, flag2 ? ("关键字[" + selectedText + "]") : "[电子病历系统知识库]", false, true);
            KB_Item myItem = obj2 as KB_Item;
            if (myItem != null)
            {
                if (flag)
                {
                    this.myContent.DeleteSeleciton();
                }
                num = this._InsertKB(myItem.OwnerList, myItem);
                this.Modified = true;
                this.EndUpdate();
                this.EndContentChangeLog();
                return num;
            }
            KB_List myList = obj2 as KB_List;
            if (myList != null)
            {
                num = this._InsertKB(myList);
            }
            return num;
        }

        /// <summary>
        /// 更新输入元素
        /// </summary>
        /// <param name="text"></param>
        public void _updateInput(string text, ZYTextInput _input)
        {
            this.BeginContentChangeLog();
            _input.Source = text;
            _input.SelectType = "1";
            _input.Text = text;
            this.EndContentChangeLog();
            this.ContentChanged();
            _input.setMoveStart();
        }
        /// <summary>
        /// 插入关键字
        /// </summary>
        /// <param name="myList"></param>
        /// <returns></returns>
        public int _InsertKB(KB_List myList)
        {
            return this._InsertKB(myList, null);
        }

        public void _InsertKB(string text, string id)
        {
            if (this.Locked)
            {
                return;
            }
            if (text != "" && id != "")
            {
                try
                {
                    ZYTextElement currentElement = this.myContent.CurrentElement;
                    this.BeginUpdate();
                    this.BeginContentChangeLog();
                    ZYTextInput select = new ZYTextInput();
                    select.SelectType = "1";
                    select.OwnerDocument = this;
                    select.Name = text;
                    select.Text = text;
                    select.ListSource = id;
                    select.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);
                    this.myContent.AutoClearSelection = true;
                    this.myContent.InsertElement(select);
                    this.myContent.CurrentElement = currentElement;
                    this.myContentChangeLog.strUndoName = "插入下拉列表 " + text;
                    this.EndContentChangeLog();
                    this.EndUpdate();
                    this.ContentChanged();
                }
                catch (Exception exception)
                {
                    ZYErrorReport.Instance.SourceException = exception;
                    ZYErrorReport.Instance.SourceObject = text;
                    ZYErrorReport.Instance.UserMessage = "插入知识点 " + text + " 错误";
                    ZYErrorReport.Instance.MemberName = "Document._InsertKB";
                    ZYErrorReport.Instance.ReportError();
                }
            }
        }

        public void _InsertKB(string text, string id, string type, string name)
        {
            if (this.Locked)
            {
                return;
            }
            if (text != "" && id != "")
            {
                try
                {
                    ZYTextElement currentElement = this.myContent.CurrentElement;
                    this.BeginUpdate();
                    this.BeginContentChangeLog();
                    ZYTextInput select = new ZYTextInput();
                    select.SelectType = "1";
                    select.OwnerDocument = this;
                    select.Name = name;
                    select.Text = text;
                    select.ListSource = id;
                    select.SelectType = type;
                    select.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);
                    this.myContent.AutoClearSelection = true;
                    this.myContent.InsertElement(select);
                    this.myContent.CurrentElement = currentElement;
                    this.myContentChangeLog.strUndoName = "插入下拉列表 " + text;
                    this.EndContentChangeLog();
                    this.EndUpdate();
                    this.ContentChanged();
                }
                catch (Exception exception)
                {
                    ZYErrorReport.Instance.SourceException = exception;
                    ZYErrorReport.Instance.SourceObject = text;
                    ZYErrorReport.Instance.UserMessage = "插入知识点 " + text + " 错误";
                    ZYErrorReport.Instance.MemberName = "Document._InsertKB";
                    ZYErrorReport.Instance.ReportError();
                }
            }
        }

        public int _InsertKB(KB_List myList, KB_Item myItem)
        {
            if ((this.Locked || (myList == null)))
            {
                return -1;
            }


            int num = -1;
            if (!myList.HasLaunchSystemItems)
            {
                myList.LaunchSystemItems(this.myDataSource.DBConn);
            }
            if (myList != null)
            {
                try
                {
                    this.Loading = true;
                    myList.RefCount++;
                    ZYTextElement currentElement = this.myContent.CurrentElement;
                    if ((myItem != null) && myItem.isTemplate())
                    {
                        if (this._InsertDocument(myItem.ItemValue))
                        {
                            num = 0;
                        }
                        else
                        {
                            num = -1;
                        }
                    }
                    else if (myList.InputBoxAttribute)
                    {
                        ZYTextInput newElement = new ZYTextInput();
                        newElement.OwnerDocument = this;
                        newElement.ListSource = myList.SEQ;
                        newElement.Name = myList.Name;
                        newElement.Unit = myList.Desc;
                        this.myContent.AutoClearSelection = true;
                        this.BeginContentChangeLog();
                        this.BeginUpdate();
                        if (myList.PreAppendNameAttribute)
                        {
                            this.myContent.InsertString(myList.Name);
                        }
                        if (myItem != null)
                        {
                            newElement.Text = myItem.ItemText;
                        }
                        this.myContent.InsertElement(newElement);
                        if (myList.AfterAppendNameAttribute)
                        {
                            this.myContent.CurrentElement = currentElement;
                            this.myContent.InsertString(myList.Name);
                        }
                        this.myContentChangeLog.strUndoName = "插入文本框" + myList.Name;
                        this.EndUpdate();
                        this.myContent.SetSelection(newElement.Index + 1, 0);
                        if (this.myOwnerControl != null)
                        {
                            this.myOwnerControl.Focus();
                        }
                        this.EndContentChangeLog();
                        num = 1;
                    }
                    else if (myList.HasItems())
                    {
                        ZYTextSelect select = new ZYTextSelect();
                        select.OwnerDocument = this;
                        select.Name = myList.Name;
                        select.ListSource = myList.SEQ;
                        select.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);

                        if (myItem == null)
                        {
                            select.Text = myList.Name;
                            select.Value = myList.Name;
                        }
                        else
                        {
                            select.Text = myItem.ItemText;// myItem.ItemValue;//
                            select.Value = myItem.ItemText;// StringCommon.isBlankString(myItem.ItemValue) ? myItem.ItemText : myItem.ItemText;
                        }
                        //(新加的属性)*********************
                        if ((select.Sign == null) || (select.Sign.Equals("")))
                            select.Sign = "值:" + select.Value + ",创建时间:" + (DateTime.Now).ToString("yyyy年MM月dd日 HH:mm") + ",IP:" + this.GetUserIP();
                        //else
                        //    select.Sign = "值:" + select.Value + ",修改值:" + myItem .ItemText +",修改时间:" + DateTime.Now + ",IP:" + this.GetUserIP();//myItem.ItemValue 
                        if (!myList.TempSign.Equals(""))
                        {
                            select.Sign = "值:" + myList.TempValue + ",修改值:" + myItem.ItemText + ",修改时间:" + (DateTime.Now).ToString("yyyy年MM月dd日 HH:mm") + ",IP:" + this.GetUserIP() + "|" + myList.TempSign;
                        }

                        this.myContent.AutoClearSelection = true;
                        this.BeginContentChangeLog();
                        this.BeginUpdate();
                        if (myList.PreAppendNameAttribute)
                        {
                            this.myContent.InsertString(myList.Name);
                        }
                        this.myContent.InsertElement(select);
                        if (myList.AfterAppendNameAttribute)
                        {
                            this.myContent.InsertString(myList.Name);
                        }
                        this.myContent.CurrentElement = currentElement;
                        this.myContentChangeLog.strUndoName = "插入下拉列表 " + myList.Name;
                        this.EndUpdate();
                        if (this.myOwnerControl != null)
                        {
                            this.myOwnerControl.Focus();
                        }
                        this.EndContentChangeLog();
                        if (myItem == null)
                        {
                            num = 2;
                        }
                        else
                        {
                            num = 3;
                        }
                    }
                }
                catch (Exception exception)
                {
                    ZYErrorReport.Instance.SourceException = exception;
                    ZYErrorReport.Instance.SourceObject = myList;
                    ZYErrorReport.Instance.UserMessage = "插入知识点 " + myList.Name + " 错误";
                    ZYErrorReport.Instance.SetAttribute("KBItem", (myItem == null) ? "[null]" : myItem.ItemText);
                    ZYErrorReport.Instance.MemberName = "Document._InsertKB";
                    ZYErrorReport.Instance.ReportError();
                }
                this.Loading = false;
            }
            return num;
        }

        public int _InsertKB(KB_Item myItem, int type)
        {
            int num = -1;

            this.Loading = true;
            //myList.RefCount++;
            ZYTextElement currentElement = this.myContent.CurrentElement;
            ZYTextSelect select = new ZYTextSelect();
            select.OwnerDocument = this;
            select.Name = myItem.ItemValue;
            select.ListSource = "0";
            select.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);
            select.Text = myItem.ItemValue;//myItem.ItemText;
            select.Value = myItem.ItemValue;//StringCommon.isBlankString(myItem.ItemValue) ? myItem.ItemText : myItem.ItemText;            

            //(新加的属性)*********************
            if ((select.Sign == null) || (select.Sign.Equals("")))
                select.Sign = "值:" + select.Value + ",创建时间:" + (DateTime.Now).ToString("yyyy年MM月dd日 HH:mm") + ",IP:" + this.GetUserIP();
            else
                select.Sign = "值:" + select.Value + ",修改值:" + myItem.ItemValue + ",修改时间:" + (DateTime.Now).ToString("yyyy年MM月dd日 HH:mm") + ",IP:" + this.GetUserIP();

            this.myContent.AutoClearSelection = true;
            this.BeginContentChangeLog();
            this.BeginUpdate();
            //if (myList.PreAppendNameAttribute)
            //{
            //    this.myContent.InsertString(myItem.ItemValue);
            //}
            this.myContent.InsertElement(select);
            //if (myList.AfterAppendNameAttribute)
            //{
            //    this.myContent.InsertString(myItem.ItemValue);
            //}
            this.myContent.CurrentElement = currentElement;
            this.myContentChangeLog.strUndoName = "插入下拉列表 " + myItem.ItemValue;
            this.EndUpdate();
            if (this.myOwnerControl != null)
            {
                this.myOwnerControl.Focus();
            }
            this.EndContentChangeLog();
            if (myItem == null)
            {
                num = 2;
            }
            else
            {
                num = 3;
            }

            return num;
        }




        /// <summary>
        /// 插入下拉列表
        /// </summary>
        /// <param name="mySelect"></param>
        /// <returns></returns>
        public ZYTextSelect _InsertSelect(ZYTextSelect mySelect)
        {
            if (this.Locked)
            {
                return null;
            }
            this.BeginContentChangeLog();
            this.BeginUpdate();
            if (this.myContent.HasSelected())
            {
                this.myContent.DeleteSeleciton();
            }
            else if (!this.myOwnerControl.InsertMode)
            {
                this.myContent.DeleteCurrentElement();
            }
            this.myContent.AutoClearSelection = true;
            this.myContent.InsertElement(mySelect);
            this.myContentChangeLog.strUndoName = "插入下拉列表 " + mySelect.Name;
            this.EndUpdate();
            this.EndContentChangeLog();
            return mySelect;
        }

        public void LoadAllData()
        {
            try
            {
                string ownerSection = ZYKBBuffer.Instance.OwnerSection;
                ZYKBBuffer.Instance.OwnerSection = null;
                ZYKBBuffer.Instance.LoadAllKBList(true);
                ZYKBBuffer.Instance.OwnerSection = ownerSection;
                ZYKBBuffer.Instance.LoadKBSection();
            }
            catch (Exception exception)
            {
                ZYErrorReport.Instance.Clear();
                ZYErrorReport.Instance.SourceException = exception;
                ZYErrorReport.Instance.SourceObject = ZYKBBuffer.Instance;
                ZYErrorReport.Instance.UserMessage = "加载知识库错误";
                ZYErrorReport.Instance.MemberName = "frmText.LoadAllData";
                ZYErrorReport.Instance.ShowErrorDialog();
            }
        }

        /***
         * 插入时间
         */
        public void _InsertTime(string time, string formatTime)
        {
            if (!this.Locked)
            {
                this.BeginContentChangeLog();
                this.BeginUpdate();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }

                ZYTextTime ztt = new ZYTextTime();
                ztt.OwnerDocument = this;
                ztt.Value = time;
                ztt.Name = "时间域";
                ztt.Text = formatTime;
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(ztt);
                this.myContentChangeLog.strUndoName = "插入时间域" + time;
                this.EndUpdate();
                this.EndContentChangeLog();
            }

        }

        /***
         * 插入药库
         */
        public void _InsertMedicine(string id, string text)
        {
            if (!this.Locked)
            {
                this.BeginContentChangeLog();
                this.BeginUpdate();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }

                ZYTextMedicine zym = new ZYTextMedicine();
                zym.OwnerDocument = this;
                zym.Value = id;
                zym.Name = "药库";
                zym.Text = text;

                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(zym);
                this.myContentChangeLog.strUndoName = "插入药库" + text;
                this.EndUpdate();
                this.EndContentChangeLog();
            }

        }

        public ZYTextSelect _InsertSelect(string strName, string strList, bool bolMultiple)
        {
            if (!this.Locked)
            {
                if (ZYKBBuffer.Instance.RootList.ChildNodes == null)
                {
                    LoadAllData();
                }
                object objValue = this.myOwnerControl.ShowKBPopupList(this.myContent.CurrentElement, ZYKBBuffer.Instance.RootList.ChildNodes, "插入下拉列表", bolMultiple, true);
                if (objValue != null)
                {
                    this.BeginContentChangeLog();
                    this.BeginUpdate();
                    if (this.myContent.HasSelected())
                    {
                        this.myContent.DeleteSeleciton();
                    }
                    else if (!this.myOwnerControl.InsertMode)
                    {
                        this.myContent.DeleteCurrentElement();
                    }
                    ZYTextSelect newElement = new ZYTextSelect();
                    newElement.Multiple = bolMultiple;
                    newElement.Name = strName;
                    this.myContent.AutoClearSelection = true;
                    this.myContent.InsertElement(newElement);

                    newElement.SetValue(objValue, true);
                    this.myContentChangeLog.strUndoName = "插入下拉列表 " + strName;
                    this.EndUpdate();
                    this.EndContentChangeLog();
                    return newElement;
                }
            }
            return null;
        }

        public void _InsertFixedInput(int width)
        {
            if (!this.Locked)
            {
                this.BeginContentChangeLog();
                this.BeginUpdate();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }

                ZYTextFixedInput zym = new ZYTextFixedInput();
                zym.OwnerDocument = this;
                zym.FixedWidth = width;
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(zym);
                this.myContentChangeLog.strUndoName = " ";
                this.EndUpdate();
                this.EndContentChangeLog();
            }
        }


        /// <summary>
        /// 插入表格
        /// </summary>
        /// <param name="rowCount"></param>
        /// <param name="colCount"></param>
        public void _InsertTable(int rowCount, int colCount)
        {
            if (!this.Locked)
            {
                if (this.Content.CurrentElement.RealLeft > 0)
                {
                    _InsertChar('\r');
                }
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                ZYTextTable newElement = new ZYTextTable(this, this.myContent.CurrentElement.Parent, rowCount, colCount);
                this.myContent.AutoClearSelection = true;
                this.myContent.InsertElement(newElement);
                this.myContentChangeLog.strUndoName = "插入表格";
                this.myContent.MoveSelectStart((int)(this.myContent.SelectStart - 1));
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }


        /// <summary>
        /// 插入表格行列
        /// </summary>
        /// <param name="pos"></param>
        public void _InsertTableCol(int pos)
        {
            ZYTextTable inTable = this.GetInTable(this.myContent.CurrentElement);
            if (inTable != null)
            {
                ZYTextTableRow inTableRow = this.GetInTableRow(this.myContent.CurrentElement);
                if (inTableRow != null)
                {
                    ZYTextTableCell inTableCell = this.GetInTableCell(this.myContent.CurrentElement);
                    if (inTableCell == null)
                    {
                        inTableCell = (ZYTextTableCell)inTableRow.Cells[inTableRow.CellCount - 1];
                    }
                    if (!this.Locked)
                    {
                        this.BeginUpdate();
                        this.BeginContentChangeLog();
                        if (this.myContent.HasSelected())
                        {
                            this.myContent.DeleteSeleciton();
                        }
                        else if (!this.myOwnerControl.InsertMode)
                        {
                            this.myContent.DeleteCurrentElement();
                        }
                        this.myContent.AutoClearSelection = true;
                        inTable.InsertCol(inTableRow, inTableCell, pos);
                        inTable.RefreshSize();
                        this.ContentChanged();
                        this.myContentChangeLog.strUndoName = "插入表格列";
                        this.myContent.MoveSelectStart((int)(this.myContent.SelectStart - 1));
                        this.EndContentChangeLog();
                        this.EndUpdate();
                    }
                }
            }
        }

        /// <summary>
        /// 插入表格行
        /// </summary>
        /// <param name="pos"></param>
        public void _InsertTableRow(int pos)
        {
            ZYTextTableRow inTableRow = this.GetInTableRow(this.myContent.CurrentElement);
            if ((inTableRow != null) && !this.Locked)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                if (this.myContent.HasSelected())
                {
                    this.myContent.DeleteSeleciton();
                }
                else if (!this.myOwnerControl.InsertMode)
                {
                    this.myContent.DeleteCurrentElement();
                }
                this.myContent.AutoClearSelection = true;
                ZYTextTableRow newElement = inTableRow.OwnerTable._InsertRow(inTableRow, pos);
                this.myContent.InsertElement(inTableRow.OwnerTable, newElement, inTableRow, pos);
                this.myContentChangeLog.strUndoName = "插入表格行";
                this.myContent.MoveSelectStart((int)(this.myContent.SelectStart - 1));
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        /// <summary>
        /// 合并表格
        /// </summary>
        public void _MergeTableCell()
        {
            this.BeginUpdate();
            this.BeginContentChangeLog();
            this.myContent.AutoClearSelection = true;
            ZYTextTable inTable = this.GetInTable(this.myContent.CurrentElement);
            if (inTable != null)
            {
                int num = 1;
                int colIndex = -1;
                ZYTextTableRow row = null;
                if (inTable.SelectedCells.Count > 1)
                {
                    foreach (ZYTextTableCell cell in inTable.SelectedCells)
                    {
                        if (row != null)
                        {
                            if ((ZYTextTableRow)cell.Parent == row)
                            {
                                num = 0;
                                break;
                            }
                        }

                        if (colIndex == -1 && row == null)
                        {
                            //colIndex = cell.ColIndex;
                            row = (ZYTextTableRow)cell.Parent;
                        }
                        //if (cell.ColIndex != colIndex)
                        //{
                        //    num = 0;
                        //    break;
                        //}                       
                    }
                }
                if (num == 0)
                {
                    ArrayList selectElements = this.myContent.GetSelectTableElements();
                    if (selectElements.Count >= 2)
                    {
                        ZYTextTableCell item = null;
                        ArrayList cells = new ArrayList();
                        for (int i = 0; i < selectElements.Count; i++)
                        {
                            if (((item = this.GetInTableCell((ZYTextElement)selectElements[i])) != null) && !cells.Contains(item))
                            {
                                if (inTable.SelectedCells.Contains(item))
                                {
                                    cells.Add(item);
                                }
                            }
                        }
                        if (cells.Count >= 2)
                        {
                            ZYTextTableRow ownerRow = ((ZYTextTableCell)cells[0]).OwnerRow;
                            inTable.MergeTableHCell(ownerRow, cells);
                            inTable.RefreshSize();
                            this.ContentChanged();
                        }
                    }
                }
                else if (num == 1)
                {
                    inTable.MergeTableVCell();
                    inTable.RefreshSize();
                }
            }
            this.myContentChangeLog.strUndoName = "插入字符串";
            this.EndContentChangeLog();
            this.EndUpdate();
            this.ContentChanged();
        }

        public void _MoveDown()
        {
            this.myContent.MoveDownOneLine();
            this.UpdateCaret();
        }

        public void _MoveEnd()
        {
            this.myContent.MoveEnd();
            this.UpdateCaret();
        }

        public void _MoveHome()
        {
            this.myContent.MoveHome();
            this.UpdateCaret();
        }

        public void _MoveLeft()
        {
            this.myContent.MoveLeft();
            this.UpdateCaret();
        }

        public void _MoveRight()
        {
            this.myContent.MoveRight();
            this.UpdateCaret();
        }

        public void _MoveUp()
        {
            this.myContent.MoveUpOneLine();
            this.UpdateCaret();
        }

        /// <summary>
        /// 下一页
        /// </summary>
        public void _PageDown()
        {
            this.myContent.MoveStep(this.myOwnerControl.ClientSize.Height);
            this.UpdateCaret();
        }

        /// <summary>
        /// 上一页
        /// </summary>
        public void _PageUp()
        {
            this.myContent.MoveStep(-this.myOwnerControl.ClientSize.Height);
            this.UpdateCaret();
        }

        //private bool CanPaste
        //{
        //    get
        //    {
        //        System.Diagnostics.Process myproc = new System.Diagnostics.Process();
        //        try
        //        {
        //            foreach (Process thisproc in Process.GetProcessesByName(processName))
        //            {
        //                if (!thisproc.CloseMainWindow())
        //                {
        //                    { }
        //                }
        //            }
        //        }
        //        catch (Exception Exc)
        //        {
        //        }
        //        GC.Collect();
        //    }
        //}

        /// <summary>
        /// 粘贴
        /// </summary>
        public void _Paste()
        {
            if (!this.Locked)
            {
                try
                {
                    IDataObject dataObject = Clipboard.GetDataObject();
                    if (dataObject.GetDataPresent("emrtextdocument2005"))
                    {
                        XmlDocument document = new XmlDocument();
                        document.PreserveWhitespace = true;
                        string data = (string)dataObject.GetData("emrtextdocument2005");
                        document.LoadXml(data);

                        if (!this.canCopyPaste && this.Us.InpatientInfo != null && document.DocumentElement.Attributes["inpatient_id"] != null && document.DocumentElement.Attributes["inpatient_id"].Value != this.Us.InpatientInfo.Id.ToString())
                        {
                            App.Msg("您复制的数据不是同一个病人的!所以不能粘贴！");
                            return;
                        }
                        ArrayList myList = new ArrayList();
                        this.LoadElementsToList(document.DocumentElement, myList);
                        if (myList.Count > 0)
                        {
                            foreach (ZYTextElement element in myList)
                            {
                                if (element is ZYTextContainer)
                                {
                                    (element as ZYTextContainer).ClearSaveLog();
                                }
                                element.RefreshSize();
                            }
                            this.BeginUpdate();
                            this.BeginContentChangeLog();
                            if (this.myContent.HasSelected())
                            {
                                this.myContent.DeleteSeleciton();
                            }
                            this.myContent.InsertRangeElements(myList);
                            this.EndContentChangeLog();
                            this.EndUpdate();
                        }
                    }
                    else
                    {
                        if (!this.canCopyPaste && this.Us.InpatientInfo != null)
                        {
                            App.Msg("禁止外部编辑器的内容复制至病历录入界面！");
                            return;
                        }
                        string textFromClipboard = ClipboardHandler.GetTextFromClipboard();
                        if (textFromClipboard != null)
                        {
                            this.BeginUpdate();
                            this.BeginContentChangeLog();
                            this.myContent.ReplaceSelection(textFromClipboard);
                            this.myContentChangeLog.strUndoName = "粘贴";
                            this.EndContentChangeLog();
                            this.EndUpdate();
                        }
                    }
                }
                catch (Exception exception)
                {
                    ZYErrorReport.Instance.DebugPrint("试图粘贴数据错误:" + exception.ToString());
                }
            }
        }

        /// <summary>
        /// 返回下一步操作
        /// </summary>
        /// <returns></returns>
        public bool _Redo()
        {
            if ((this.intUndoState == 0) && (this.myRedoList.Count > 0))
            {
                this.intUndoState = 2;
                A_Action action = (A_Action)this.myRedoList[this.myRedoList.Count - 1];
                this.myRedoList.RemoveAt(this.myRedoList.Count - 1);
                action.Redo();
                if (action.SelectStart2 >= 0)
                {
                    this.myContent.SetSelection(action.SelectStart2, action.SelectLength2);
                }
                this.myUndoList.Add(action);
                this.intUndoState = 0;
            }
            return true;
        }

        /// <summary>
        /// 替换
        /// </summary>
        /// <param name="strFind"></param>
        /// <param name="strReplace"></param>
        public void _Replace(string strFind, string strReplace)
        {
            this.BeginUpdate();
            this.BeginContentChangeLog();
            this.myContent.ReplaceText(strFind, strReplace);
            this.myContentChangeLog.strUndoName = "替换";
            this.EndContentChangeLog();
            this.EndUpdate();
        }

        /// <summary>
        /// 替换所有
        /// </summary>
        /// <param name="strFind"></param>
        /// <param name="strReplace"></param>
        public void _ReplaceAll(string strFind, string strReplace)
        {
            this.BeginUpdate();
            this.BeginContentChangeLog();
            this.myContent.ReplaceTextAll(strFind, strReplace);
            this.myContentChangeLog.strUndoName = "替换所有";
            this.EndContentChangeLog();
            this.EndUpdate();
        }

        /// <summary>
        /// 重设尺寸
        /// </summary>
        /// <param name="myObj"></param>
        /// <param name="NewWidth"></param>
        /// <param name="NewHeight"></param>
        /// <returns></returns>
        public bool _Resize(ZYTextObject myObj, int NewWidth, int NewHeight)
        {
            if (((myObj != null) && myObj.CanResize) && ((myObj.Width != NewWidth) && (myObj.Height != NewHeight)))
            {
                myObj.Width = NewWidth;
                myObj.Height = NewHeight;
                this.RefreshLine();
                this.UpdateView();
                this.myContent.CurrentSelectElement = myObj;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 全选
        /// </summary>
        public void _SelectAll()
        {
            this.myContent.SelectAll();
        }

        /// <summary>
        /// 撤销操作
        /// </summary>
        /// <returns></returns>
        public bool _Undo()
        {
            if ((this.intUndoState == 0) && (this.myUndoList.Count > 0))
            {
                this.intUndoState = 1;
                A_Action action = (A_Action)this.myUndoList[this.myUndoList.Count - 1];
                this.myUndoList.RemoveAt(this.myUndoList.Count - 1);
                if (action.Undo())
                {
                    this.myRedoList.Add(action);
                    this.intUndoState = 0;
                    this.ContentChanged();
                    if (action.SelectStart >= 0)
                    {
                        this.myContent.SetSelection(action.SelectStart, action.SelectLength);
                    }
                    return true;
                }
                this.intUndoState = 0;
            }
            this.ContentChanged();
            return false;
        }


        /// <summary>
        /// 添加数据源查询名称
        /// </summary>
        /// <param name="myElement"></param>
        private void AddDataSourceQueryName(XmlElement myElement)
        {
            if (((myElement.Name == "span") || (myElement.Name == "select")) && myElement.HasAttribute("source"))
            {
                string attribute = myElement.GetAttribute("source");
                if ((attribute != null) && (attribute.Trim().Length > 0))
                {
                    attribute = attribute.Trim();
                    this.myDataSource.AddQueryName(attribute);
                }
            }
            if ((myElement.Name == "select") && myElement.HasAttribute("listsource"))
            {
                string strName = myElement.GetAttribute("listsource");
                if ((strName != null) && (strName.Trim().Length > 0))
                {
                    strName = strName.Trim();
                    this.myDataSource.AddQueryName(strName);
                }
            }
            foreach (XmlNode node in myElement.ChildNodes)
            {
                if (node is XmlElement)
                {
                    this.AddDataSourceQueryName(node as XmlElement);
                }
            }
        }

        public void AddLine(ZYTextLine myLine)
        {
            this.myLines.Add(myLine);
        }

        internal bool BeforeInsertElemnt(ZYTextContainer container, ZYTextElement NewElement)
        {
            if (!this.bolLoading)
            {
                if (this.myContentChangeLog != null)
                {
                    this.myContentChangeLog.CanLog = false;
                }
                NewElement.DeleterIndex = -1;
                NewElement.CreatorIndex = this.mySaveLogs.CurrentIndex;
                ZYTextChar ch = NewElement as ZYTextChar;
                if (ch != null)
                {
                    //(新增)当元素是新创建的时候，给元素临时颜色显示默认为黑色********************
                    if (ch.ForeColor != null)
                    {
                        ch.TempForeColor = ch.ForeColor;
                    }
                    else
                    {
                        ch.ForeColor = Color.Black;//******
                        ch.TempForeColor = Color.Black;
                    }
                    //****************
                    if (this.myMarks.Count >= 2)
                    {
                        ch.ForeColor = Color.DarkRed;
                    }
                }
                if (this.myContentChangeLog != null)
                {
                    this.myContentChangeLog.CanLog = true;
                }

            }
            //(新增)当在编辑区域新增的元素是从xml文档中读取的时候，先读出每个元素的颜色值赋给临时颜色值变量***********************
            //记录初始颜色
            else
            {
                ZYTextChar ch = NewElement as ZYTextChar;
                if (ch != null)
                {
                    Color tempColor = ch.intForeColor;
                    ch.TempForeColor = tempColor;
                }
            }

            return true;
        }

        public void BeginContentChangeLog()
        {
            if (this.intLogLevel <= 0)
            {
                this.myContentChangeLog = new A_ContentChangeLog();
                this.myContentChangeLog.OwnerDocument = this;
                this.myContentChangeLog.SelectStart = this.myContent.SelectStart;
                this.myContentChangeLog.SelectLength = this.myContent.SelectLength;
            }
            this.intLogLevel++;
        }

        public void BeginUpdate()
        {
            if (this.myOwnerControl != null)
            {
                this.myOwnerControl.BeginUpdate();
            }
        }

        /// <summary>
        /// 判断是否可以修改
        /// </summary>
        /// <returns></returns>
        public bool CanModify()
        {
            return !this.Locked;
        }

        /// <summary>
        /// 判断系统是否加载知识库
        /// </summary>
        /// <returns></returns>
        public bool CheckKBLoaded()
        {
            if (ZYKBBuffer.Instance.CanReadKB())
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 清除编辑区的所有内容
        /// </summary>
        public void ClearContent()
        {
            this.myMarks.Clear();
            this.myUndoList.Clear();
            this.myRedoList.Clear();
            this.myContentChangeLog = null;
            foreach (ZYTextElement element in this.myElements)
            {
                if (element is IDisposable)
                {
                    (element as IDisposable).Dispose();
                }
            }
            this.myDocumentElement = new ZYTextDiv();
            this.myDocumentElement.OwnerDocument = this;
            this.mySaveLogs.Clear();
            this.myDataSource.ClearQueryNames();
            this.myDataSource.ClearQueryVariables();
            this.myInfo.Title = "";
            this.myInfo.ID = "";
            this.RefreshElements();
            this.RefreshSize();
            this.RefreshLine();
            this.myContent.SetSelection(0, 0);
            this.Refresh();
        }

        /// <summary>
        /// 当编辑区内容发生变化时触发
        /// </summary>
        public void ContentChanged()
        {
            this.bolLastContentChangedFlag = true;
            this.RefreshElements();
            this.RefreshLine();
            this.myView.Height = this.myDocumentElement.Top + this.myDocumentElement.Height;
            if (this.myOwnerControl == null)
                this.myOwnerControl = new UcEditorControl();
            if (this.OnContentChanged != null)
            {
                this.OnContentChanged(this, null);
            }
            this.myOwnerControl.UpdateSmartTag();
            this.OwnerControl.UpdateTextCaret();
        }

        /// <summary>
        /// 创建所有对象
        /// 在All属性中用到，可是All属性却没有被用到
        /// </summary>
        /// <returns></returns>
        private object CreateAllObject()
        {
            if (this.myContainters.Count == 0)
            {
                return new object();
            }
            AssemblyName name = new AssemblyName();
            name.Name = "RunTimeZYTextDocumentLib";
            TypeBuilder tb = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run).DefineDynamicModule("RunTimeZYTextModule").DefineType("AllElements", TypeAttributes.Public);
            Hashtable myNames = new Hashtable();
            foreach (object obj2 in this.myContainters)
            {
                if (obj2 is ZYTextContainer)
                {
                    this.InnerDefineField(((ZYTextContainer)obj2).Name, tb, myNames, obj2);
                    this.InnerDefineField(((ZYTextContainer)obj2).ID, tb, myNames, obj2);
                }
                else if (obj2 is ZYTextObject)
                {
                    this.InnerDefineField(((ZYTextObject)obj2).ID, tb, myNames, obj2);
                }
            }
            Type type = tb.CreateType();
            object target = Activator.CreateInstance(type);
            foreach (FieldInfo info in type.GetFields())
            {
                if (myNames.ContainsKey(info.Name))
                {
                    type.InvokeMember(info.Name, BindingFlags.SetField, null, target, new object[] { myNames[info.Name] });
                }
            }
            return target;
        }

        /// <summary>
        /// 创建字符
        /// </summary>
        /// <param name="vChar"></param>
        /// <returns></returns>
        public ZYTextChar CreateChar(char vChar)
        {
            ZYTextChar ch = ZYTextChar.Create(vChar);
            ch.OwnerDocument = this;
            ch.CreatorIndex = this.mySaveLogs.CurrentIndex;
            if (isEnglishNum(vChar))
            {
                ch.Font = this.myView.DefaultEnglishNumFont;
            }
            else
            {
                ch.Font = this.myView.DefaultFont;
            }
            ch.Visible = true;
            return ch;
        }

        public bool isEnglishNum(char ch)
        {
            return englishNumFontStr.IndexOf(ch) >= 0;
        }

        public bool isHalf(char ch)
        {
            return englishHalf.IndexOf(ch) >= 0;
        }

        public ArrayList CreateChars(string strText, ZYTextContainer vParent)
        {
            ArrayList list = new ArrayList();
            ZYTextChar ch = null;
            foreach (char ch2 in strText)
            {
                if ((ch2 != '\r') || (ch2 != '\n'))
                {
                    ch = this.CreateChar(ch2);
                    if (ch != null)
                    {
                        ch.Parent = vParent;
                        ch.OperaterCreater = vParent.OperaterCreater;////////
                        //ch.OperaterCreater = Convert.ToString(this.SaveLogs.Count - 1);
                        //ch.Parent.ForeColor = Color.Blue;
                        //ch.ForeColor = Color.Blue;
                        //ch .TempForeColor = Color .Blue ;
                        list.Add(ch);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 创建HTML元素
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public virtual ZYTextElement CreateElement(string strName)
        {
            ZYTextElement element = null;
            if ((strName == null) || (strName.Trim().Length == 0))
            {
                return null;
            }
            strName = strName.Trim();
            switch (strName)
            {
                case "br":
                    element = new ZYTextLineEnd();
                    break;

                case "p":
                    element = new ZYTextParagraph();
                    break;

                case "body":
                    element = new ZYTextDiv();
                    break;

                case "div":
                    element = new ZYTextDiv();
                    break;

                case "numinput":
                    element = new ZYTextNumInput();
                    break;
                case "select":
                    element = new ZYTextSelect();
                    break;
                case "media":
                    element = new ZYTextMedia();
                    break;
                case "time":
                    element = new ZYTextTime();
                    break;
                case "Skip":
                    element = new ZYTextSkipSign();
                    break;
                case "img":
                    element = new ZYTextImage();
                    break;
                case "medicine":
                    element = new ZYTextMedicine();
                    break;
                case "input":
                    element = new ZYTextInput();
                    break;
                case "fixedinput":
                    element = new ZYTextFixedInput();
                    break;
                case "split":
                    element = new ZYTextSplit();
                    break;
                case "checkbox":
                    element = new ZYTextCheck();
                    break;

                case "hr":
                    element = new ZYTextHRule();
                    break;
                case "radiobutton":
                    element = new ZYTextRadio();
                    break;
                case "keyword":
                    element = new ZYTextKeyWord();
                    break;

                case "table":
                    element = new ZYTextTable();
                    break;

                case "borderinput":
                    element = new ZYTextBorderInput();
                    break;

                case "row":
                    element = new ZYTextTableRow();
                    break;

                case "cell":
                    element = new ZYTextTableCell();
                    break;

                case "structemr":
                    element = new ZYTextStruct();
                    break;

                case "bapf":
                    element = new ZYTextBapfMark();
                    break;
            }
            if (element != null)
            {
                element.OwnerDocument = this;
                element.CreatorIndex = this.mySaveLogs.CurrentIndex;
            }
            return element;
        }

        public ZYTextElement CreateElementByXML(XmlElement myElement)
        {
            if (myElement != null)
            {
                ZYTextElement element = this.CreateElement(myElement.Name);
                if (element != null)
                {
                    this.FillDataSource(myElement);
                    element.FromXML(myElement);
                    element.OwnerDocument = this;
                    return element;
                }
            }
            return null;
        }

        public void Dispose()
        {
            if (this.myView != null)
            {
                this.myView.Dispose();
            }
            if ((this.myDataSource != null) && (this.myDataSource.DBConn != null))
            {
                this.myDataSource.DBConn.Dispose();
            }
            if (this.myZYVBEngine != null)
            {
                this.myZYVBEngine.Close();
            }
            foreach (ZYTextElement element in this.myElements)
            {
                if (element is IDisposable)
                {
                    (element as IDisposable).Dispose();
                }
            }
        }

        /// <summary>
        /// 绘制所有
        /// </summary>
        /// <returns></returns>
        private bool DrawAll()
        {
            this.RefreshLine();
            this.myDocumentElement.RefreshView();
            return true;
        }

        /// <summary>
        /// 绘制删除线
        /// </summary>
        /// <param name="intLevel"></param>
        /// <param name="vLeft"></param>
        /// <param name="vTop"></param>
        /// <param name="vWidth"></param>
        /// <param name="vHeight"></param>
        public void DrawDeleteLine(int intLevel, int vLeft, int vTop, int vWidth, int vHeight)
        {
            if (this.myInfo.ShowMark)
            {
                this.myView.DrawDeleteLine(vLeft, vTop, vWidth, vHeight, (intLevel <= 1) ? 1 : 2);
            }
        }

        /// <summary>
        /// 绘制新的背景区域
        /// </summary>
        /// <param name="intLevel"></param>
        /// <param name="vLeft"></param>
        /// <param name="vTop"></param>
        /// <param name="vWidth"></param>
        /// <param name="vHeight"></param>
        public void DrawNewBackGround(int intLevel, int vLeft, int vTop, int vWidth, int vHeight)
        {
            if (this.myInfo.ShowMark)
            {
                switch (intLevel)
                {
                    case 0:
                        this.myView.FillRectangle(SystemColors.Info, vLeft, vTop, vWidth, vHeight);
                        return;

                    case 1:
                        this.myView.FillRectangle(SystemColors.Info, vLeft, vTop, vWidth, vHeight);
                        this.myView.DrawLine(SystemColors.Highlight, vLeft, (vTop + vHeight) - 1, vLeft + vWidth, (vTop + vHeight) - 1);
                        return;
                }
                this.myView.FillRectangle(SystemColors.Info, vLeft, vTop, vWidth, vHeight);
                this.myView.DrawLine(SystemColors.Highlight, vLeft, (vTop + vHeight) - 1, vLeft + vWidth, (vTop + vHeight) - 1);
                this.myView.DrawLine(SystemColors.Highlight, vLeft, (vTop + vHeight) - 3, vLeft + vWidth, (vTop + vHeight) - 3);
            }
        }

        public void EndContentChangeLog()
        {
            this.intLogLevel--;
            if (this.intLogLevel <= 0)
            {
                if ((this.myContentChangeLog != null) && this.myContentChangeLog.isEnable())
                {
                    this.myContentChangeLog.SelectStart2 = this.myContent.SelectStart;
                    this.myContentChangeLog.SelectLength2 = this.myContent.SelectLength;
                    this.RegisterUndo(this.myContentChangeLog);
                    this.myContentChangeLog = null;
                }
                this.intLogLevel = 0;
            }
        }

        public void EndUpdate()
        {
            if (this.myOwnerControl != null)
            {
                //if (this.ElementsDirty)
                //{
                //    this.RefreshElements();
                //    this.RefreshLine();
                //}
                this.myOwnerControl.EndUpdate();
                if (this.myOwnerControl.CanUpdate())
                {
                    this.UpdateView();
                }
            }
        }

        public void EnumElements(EnumElementHandler vHandler)
        {
            if ((this.myDocumentElement != null) && (vHandler != null))
            {
                this.myDocumentElement.EnumChildElements(vHandler, true);
            }
        }

        public bool FillDataSource(XmlElement myElement)
        {
            if (this.myInfo.EnableDataSource)
            {
                this.myDataSource.ClearQueryNames();
                this.AddDataSourceQueryName(myElement);
            }
            return true;
        }

        private void FillDataSourceElement(XmlElement myElement, XmlNodeList DataNodeList)
        {
            if ((myElement.Name == "select") && myElement.HasAttribute("listsource"))
            {
                string str = myElement.GetAttribute("listsource").Trim();
                foreach (XmlElement element in DataNodeList)
                {
                    if (element.GetAttribute("name") == str)
                    {
                        while (myElement.FirstChild != null)
                        {
                            myElement.RemoveChild(myElement.FirstChild);
                        }
                        foreach (XmlNode node in element.ChildNodes)
                        {
                            myElement.AppendChild(myElement.OwnerDocument.ImportNode(node, true));
                        }
                        continue;
                    }
                }
            }
            if (((myElement.Name == "span") || (myElement.Name == "select")) && myElement.HasAttribute("source"))
            {
                string str2 = myElement.GetAttribute("source").Trim();
                foreach (XmlElement element2 in DataNodeList)
                {
                    if (element2.GetAttribute("name") == str2)
                    {
                        if (myElement.Name == "span")
                        {
                            myElement.InnerText = element2.InnerText;
                        }
                        else
                        {
                            myElement.SetAttribute("value", element2.InnerText);
                        }
                        return;
                    }
                }
            }
            foreach (XmlNode node2 in myElement.ChildNodes)
            {
                if (node2 is XmlElement)
                {
                    this.FillDataSourceElement((XmlElement)node2, DataNodeList);
                }
            }
        }

        public string FixValueString(string strText)
        {
            return this.myVariables.FixVariableString(strText);
        }

        public bool FromText(string strText)
        {
            this.myDocumentElement = new ZYTextDiv();
            this.myDocumentElement.OwnerDocument = this;
            this.LoadTextElementsToList(strText, this.myDocumentElement.ChildElements);
            return true;
        }

        private string _tempTopId = "";
        public string TempTopId
        {
            set
            {
                _tempTopId = value;
            }
        }
        /// <summary>
        /// 读取XML模板元素
        /// </summary>
        /// <param name="RootElement"></param>
        /// <returns></returns>
        public bool FromXML(XmlElement RootElement)
        {
            int controlCount = this.OwnerControl.Controls.Count;
            for (int g = 0; g < controlCount; g++)
            {
                System.Windows.Forms.Control control = this.OwnerControl.Controls[g];
                if (control is LabelX || control is TextDocument.Control.AutoMsgBase)
                {
                    this.OwnerControl.Controls.Remove(control);
                    controlCount--;
                    g--;
                }
            }

            XmlElement bodyElement = GetBodyElement(RootElement);

            if (bodyElement == null)
            {
                MessageBox.Show("模板格式不正确！");
                return false;
            }
            this.Info.ShowAll = false;
            this.Info.ShowMark = false;
            this.bolLoading = true;
            this.myUndoList.Clear();
            this.myRedoList.Clear();
            RootElement.OwnerDocument.PreserveWhitespace = true;
            this.myDataSource.ClearQueryVariables();
            this.myDataSource.ClearQueryNames();
            this.mySaveLogs.Clear();
            this.myMarks.Clear();
            this.ClearContent();
            this.myDocumentElement = null;
            this.myMarks.FromXML(XMLCommon.CreateChildElement(RootElement, this.myMarks.GetXMLName(), false));
            if (this.Us.Tid != 0)
            {
                this.mySaveLogs.FromXML(XMLCommon.CreateChildElement(RootElement, this.mySaveLogs.GetXMLName(), false));
            }
            foreach (ZYTextSaveLog log in this.mySaveLogs.List)
            {
                if (this.myMarks.Count > 0)
                {
                    log.MarkLevel = this.myMarks.Count;
                }
            }
            this.myInfo.VisibleUserLevel = -1;
            this.myVariables.Clear();
            XmlElement element = XMLCommon.GetElementByName(RootElement, "values", false);
            if (element != null)
            {
                foreach (XmlNode node in element.ChildNodes)
                {
                    XmlElement element2 = node as XmlElement;
                    if (element2 != null)
                    {
                        this.myVariables.SetValue(element2.GetAttribute("name"), element2.InnerText);
                    }
                }
            }
            this.Pages.FromXML(XMLCommon.GetElementByName(RootElement, PrintPageCollection.GetXMLName(), false));
            this.myInfo.FromXML(XMLCommon.GetElementByName(RootElement, ZYDocumentInfo.GetXMLName(), false));
            this.myScript.FromXML(XMLCommon.GetElementByName(RootElement, this.myScript.GetXMLName(), false));
            this.myScript.ScriptModified = true;
            this.InvokeScriptMethod("document_preopen", null, null);
            this.Us.FromXML(XMLCommon.GetElementByName(RootElement, "head", false));
            if (bodyElement != null)
            {
                this.myDocumentElement = this.CreateElementByXML(bodyElement) as ZYTextContainer;
                if (this.myDocumentElement != null)
                {
                    this.myDocumentElement.OwnerDocument = this;
                    this.myDocumentElement.UpdateUserLogin();
                }
            }
            else
            {
                MessageBox.Show("模板格式不正确！");
                return false;
            }
            this.RefreshElementsOne();
            this.UpdateUserName();
            this.InvokeScriptMethod("document_open", null, null);
            this.bolLoading = false;
            this.Modified = false;
            ContentChanged();
            this.RefreshSize();
            this.myContent.SetSelection(0, 0);
            return true;
        }

        public bool FromXML(XmlElement RootElement, bool isIn)
        {
            int controlCount = this.OwnerControl.Controls.Count;
            for (int g = 0; g < controlCount; g++)
            {
                if (this.OwnerControl.Controls[g] is LabelX)
                {
                    this.OwnerControl.Controls.Remove(this.OwnerControl.Controls[g]);
                    controlCount--;
                    g--;
                }
            }
            XmlElement bodyElement = GetBodyElement(RootElement);
            if (bodyElement == null)
            {
                MessageBox.Show("模板格式不正确！");
                return false;
            }
            this.Info.ShowAll = false;
            this.Info.ShowMark = false;
            this.bolLoading = true;
            this.myUndoList.Clear();
            this.myRedoList.Clear();
            RootElement.OwnerDocument.PreserveWhitespace = true;
            this.myDataSource.ClearQueryVariables();
            this.myDataSource.ClearQueryNames();
            this.mySaveLogs.Clear();
            this.myMarks.Clear();
            this.ClearContent();
            this.myDocumentElement = null;
            this.myMarks.FromXML(XMLCommon.CreateChildElement(RootElement, this.myMarks.GetXMLName(), false));
            if (this.Us.Tid != 0)
            {
                this.mySaveLogs.FromXML(XMLCommon.CreateChildElement(RootElement, this.mySaveLogs.GetXMLName(), false));
            }
            foreach (ZYTextSaveLog log in this.mySaveLogs.List)
            {
                if (this.myMarks.Count > 0)
                {
                    log.MarkLevel = this.myMarks.Count;
                }
                //for (int i = 0; i < this.myMarks.Count; i++)
                //{
                //    if (log.SaveDateTime < this.myMarks[i].MarkTime)
                //    {
                //        log.MarkLevel = i;
                //    }
                //}
            }
            this.myInfo.VisibleUserLevel = -1;
            this.myVariables.Clear();
            XmlElement element = XMLCommon.GetElementByName(RootElement, "values", false);
            if (element != null)
            {
                foreach (XmlNode node in element.ChildNodes)
                {
                    XmlElement element2 = node as XmlElement;
                    if (element2 != null)
                    {
                        this.myVariables.SetValue(element2.GetAttribute("name"), element2.InnerText);
                    }
                }
            }
            this.myInfo.FromXML(XMLCommon.GetElementByName(RootElement, ZYDocumentInfo.GetXMLName(), false));
            this.myScript.FromXML(XMLCommon.GetElementByName(RootElement, this.myScript.GetXMLName(), false));
            this.myScript.ScriptModified = true;
            this.InvokeScriptMethod("document_preopen", null, null);
            this.Us.FromXML(XMLCommon.GetElementByName(RootElement, "head", false));
            if (bodyElement != null)
            {
                this.myDocumentElement = this.CreateElementByXML(bodyElement) as ZYTextContainer;
                if (this.myDocumentElement != null)
                {
                    this.myDocumentElement.OwnerDocument = this;
                    this.myDocumentElement.UpdateUserLogin();
                }
            }
            else
            {
                MessageBox.Show("模板格式不正确！");
                return false;
            }
            this.myContent.SetSelection(0, 0);
            //this.RefreshLine();
            this.RefreshElementsOne();
            this.RefreshSize();
            //this.ContentChanged();
            this.UpdateUserName();
            this.InvokeScriptMethod("document_open", null, null);
            this.bolLoading = false;
            this.Modified = false;
            ContentChanged();
            return true;
        }

        /// <summary>
        /// 设置病人基本信息
        /// </summary>
        public InPatientInfo InpatientInfo
        {
            set
            {
                if (value != null)
                    this.Us.InpatientInfo = value;
            }
        }

        /// <summary>
        /// 路径加载XML 文件
        /// </summary>
        /// <param name="strURL"></param>
        /// <returns></returns>
        public bool FromXMLFile(string strURL)
        {
            //try
            //{
            XmlDocument document = new XmlDocument();
            document.PreserveWhitespace = true;
            document.Load(strURL);
            this.myInfo.FileName = strURL;
            string strXml = string.Empty;
            //XmlNode docsetting = null;
            foreach (XmlNode node in document.DocumentElement.ChildNodes)
            {
                if (node.Name == "body")
                {
                    strXml = node.InnerXml;
                }
            }
            if (strXml != string.Empty)
            {
                this.FilterXml(strXml, document, 0);
                return true;
            }
            else
            {
                App.Msg("文件格式错误!");
                return false;
            }
            //}
            //catch
            //{
            //    App.Msg("模板格式不正确！");
            //    return false;
            //}
        }

        /// <summary>
        /// 获取当前操作
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public A_Action GetActionByName(string strName)
        {
            foreach (A_Action action in this.myActions)
            {
                if (action.ActionName() == strName)
                {
                    return action;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取XML文件中的主体节点
        /// </summary>
        /// <param name="RootElement"></param>
        /// <returns></returns>
        public static XmlElement GetBodyElement(XmlElement RootElement)
        {
            if (RootElement != null)
            {
                foreach (XmlNode node in RootElement.ChildNodes)
                {
                    if ((node.Name == "div") || (node.Name == "body"))
                    {
                        return (XmlElement)node;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 获得命令集合
        /// </summary>
        /// <returns></returns>
        public string[] GetCommandList()
        {
            string[] strArray = new string[this.myActions.Count];
            for (int i = 0; i < this.myActions.Count; i++)
            {
                strArray[i] = ((A_Action)this.myActions[i]).ActionName();
            }
            return strArray;
        }

        /// <summary>
        /// 通过ID获得元素
        /// </summary>
        /// <param name="strID"></param>
        /// <returns></returns>
        public object GetElementById(string strID)
        {
            foreach (object obj2 in this.myContainters)
            {
                if (obj2 is ZYTextContainer)
                {
                    ZYTextContainer container = obj2 as ZYTextContainer;
                    if ((container.ID == strID) || (container.Name == strID))
                    {
                        return container;
                    }
                    continue;
                }
                if (obj2 is ZYTextObject)
                {
                    ZYTextObject obj3 = obj2 as ZYTextObject;
                    if (!(obj3.ID == strID))
                    {
                        continue;
                    }
                    return obj3;
                }
            }
            return null;
        }

        public string[] GetElementKeyValueList()
        {
            ArrayList myKeyValues = new ArrayList();
            foreach (ZYTextElement element in this.myContainters)
            {
                if (!element.Deleteted && (element is ZYTextContainer))
                {
                    ((ZYTextContainer)element).AppendKeyValueList(myKeyValues);
                }
            }
            if (myKeyValues.Count > 0)
            {
                return (string[])myKeyValues.ToArray(typeof(string));
            }
            return null;
        }

        public ArrayList GetFinalElements()
        {
            ArrayList myList = new ArrayList();
            int visibleUserLevel = this.myInfo.VisibleUserLevel;
            this.myInfo.VisibleUserLevel = -1;
            bool showAll = this.myInfo.ShowAll;
            this.myInfo.ShowAll = false;
            this.myDocumentElement.AddElementToList(myList, false);
            this.myInfo.ShowAll = showAll;
            this.myInfo.VisibleUserLevel = visibleUserLevel;
            return myList;
        }

        public string GetFinalText()
        {
            return ZYTextElement.GetElementsText(this.GetFinalElements());
        }

        /// <summary>
        /// 获得表格
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public ZYTextTable GetInTable(ZYTextElement element)
        {
            if (element == null)
            {
                return null;
            }
            while (element != null)
            {
                if (element is ZYTextTable)
                {
                    return (ZYTextTable)element;
                }
                element = element.Parent;
            }
            return null;
        }

        /// <summary>
        /// 获得单元格
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public ZYTextTableCell GetInTableCell(ZYTextElement element)
        {
            while (element != null)
            {
                if (element is ZYTextTableCell)
                {
                    return (ZYTextTableCell)element;
                }
                element = element.Parent;
            }
            return null;
        }

        /// <summary>
        /// 获得表格行
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public ZYTextTableRow GetInTableRow(ZYTextElement element)
        {
            while (element != null)
            {
                if (element is ZYTextTableRow)
                {
                    return (ZYTextTableRow)element;
                }
                element = element.Parent;
            }
            return null;
        }

        internal string GetKBValue(int intKB)
        {
            return null;
        }

        /// <summary>
        /// 获得最后删除的元素
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public ZYTextElement GetLastNotDeletedElement(int index)
        {
            if ((index < 0) || (index >= this.myElements.Count))
            {
                index = this.myContent.SelectStart;
            }
            for (int i = index; i < this.myElements.Count; i++)
            {
                ZYTextElement element = (ZYTextElement)this.myElements[i];
                if (!element.Deleteted)
                {
                    return element;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取痕迹
        /// </summary>
        /// <param name="savelogindex"></param>
        /// <returns></returns>
        public int GetMarkLevel(int savelogindex)
        {
            if ((savelogindex >= 0) && (savelogindex < this.mySaveLogs.Count))
            {
                return this.mySaveLogs[savelogindex].MarkLevel;
            }
            return 0;
        }

        public ZYTextParagraph GetOwnerParagraph()
        {
            for (int i = this.myContent.SelectStart; i < this.myElements.Count; i++)
            {
                if (this.myElements[i] is ZYTextParagraph)
                {
                    return (this.myElements[i] as ZYTextParagraph);
                }
            }
            return null;
        }

        public Bitmap GetPreViewImage()
        {
            return this.GetPreViewImage(0, 0);
        }

        public Bitmap GetPreViewImage(int ImgWidth, int ImgHeight)
        {
            bool showParagraphFlag = this.myInfo.ShowParagraphFlag;
            this.myInfo.ShowParagraphFlag = false;
            this.myInfo.Printing = true;
            Bitmap bitmap = this.myView.GetBitmap(new BoolNoParameterHandler(this.RefreshSize), new BoolNoParameterHandler(this.DrawAll), ImgWidth, ImgHeight);
            this.myInfo.ShowParagraphFlag = showParagraphFlag;
            this.myInfo.Printing = false;
            return bitmap;
        }

        public Bitmap GetPreViewImage(int PageIndex, int ImgWidth, int ImgHeight)
        {
            if (ImgWidth <= 0)
            {
                ImgWidth = this.myPages.PaperWidth;
            }
            if (ImgHeight <= 0)
            {
                ImgHeight = this.myPages.PaperHeight;
            }
            Bitmap image = new Bitmap(ImgWidth, ImgHeight);
            PrintPage page = this.myPages[PageIndex];
            int pageCount = this.myPages.Count;
            using (Graphics graphics = Graphics.FromImage(image))
            {
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                graphics.Clear(Color.White);

                Graphics innerGraph = this.myView.GetInnerGraph();
                this.myView.Graph = graphics;
                this.myPages.DrawPageFrame(0, 0, graphics, false, Color.White, PageIndex + 1, this);
                this.myView.TranslateTransform(page.Left + this.myPages.LeftMargin, this.myPages.TopMargin - page.Top);
                Rectangle rect = new Rectangle(page.Left, page.Top, page.Width + 10, page.Height + ((PageIndex + 1) == pageCount ? 2 : 0));
                graphics.SetClip(rect);
                this.ViewPaint(graphics, rect);
                this.myView.Graph = innerGraph;
            }
            return image;
        }

        /// <summary>
        /// 打印单独使用此方法，不再使用A_printdocument.cs类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public void PrintEdit(int type)
        {
            ArrayList Images = new ArrayList();
            System.IO.MemoryStream mstream = null;
            for (int i = 0; i < this.Pages.Count; i++)
            {
                using (Bitmap bitmap = this.GetPreViewImage(i + 1, 0, 0))
                {
                    if (bitmap != null)
                    {
                        mstream = new System.IO.MemoryStream();///创建内存流 
                        bitmap.Save(mstream, ImageFormat.Gif);
                        byte[] bytes;
                        bytes = mstream.ToArray();
                        DataTable1 tempdate = new DataTable1();
                        tempdate.image = bytes;
                        Images.Add(tempdate);
                    }
                }
            }
            int das = 0;
            foreach (Image childImage in Images)
            {
                childImage.Save("childOne" + das.ToString());
                das++;
            }
            this.Info.ShowExpendHandle = true;
            this.Info.ShowParagraphFlag = true;
            this.Info.FieldUnderLine = true;
            GC.Collect();
        }

        public Bitmap GetPreViewImage(int PageIndex, int ImgWidth, int ImgHeight, int hei)
        {
            if (ImgWidth <= 0)
            {
                ImgWidth = this.myPages.PaperWidth;
            }
            if (ImgHeight <= 0)
            {
                ImgHeight = this.myPages.PaperHeight;
            }
            Bitmap image = new Bitmap(ImgWidth, ImgHeight);
            PrintPage page = this.myPages[PageIndex - 1];
            using (Graphics graphics = Graphics.FromImage(image))
            {
                Graphics innerGraph = this.myView.GetInnerGraph();
                this.myView.Graph = graphics;
                this.myPages.DrawPageFrame(0, 0, graphics, false, Color.White);
                this.myView.TranslateTransform(page.Left + this.myPages.LeftMargin, this.myPages.TopMargin - page.Top);
                Rectangle rect = new Rectangle(page.Left, page.Top, page.Width, page.Height);
                graphics.SetClip(rect);

                //打印的时候对打印样式的设置（是否显示下划线 段落、、）
                bool showParagraphFlag = this.myInfo.ShowParagraphFlag;
                this.myInfo.ShowParagraphFlag = false;
                this.myInfo.FieldUnderLine = false;
                this.myInfo.ShowExpendHandle = false;
                this.ViewPaint(graphics, rect);
                this.myView.Graph = innerGraph;
                this.myInfo.ShowParagraphFlag = showParagraphFlag;
                this.myInfo.Printing = false;
            }
            //对生成的打印图片进行截图   
            Bitmap image2 = this.CaptureImage(image, 640, 1086, 70, 2);

            Image im = new Bitmap(640, 1040);
            Graphics newGraphice = Graphics.FromImage(image2);
            using (Brush s = new SolidBrush(Color.White))
            {
                newGraphice.FillRectangle(s, 0, 0, 640, hei);
            }
            GC.Collect();
            image2.Save(@"D://32.jpg");
            return image2;
        }


        #region   截取图象

        ///   <summary>   
        ///   从图片中截取部分生成新图   
        ///   </summary>   
        ///   <param   name="sFromFilePath">原始图片</param>   
        ///   <param   name="saveFilePath">生成新图</param>   
        ///   <param   name="width">截取图片宽度</param>   
        ///   <param   name="height">截取图片高度</param>   
        ///   <param   name="spaceX">截图图片X坐标</param>   
        ///   <param   name="spaceY">截取图片Y坐标</param>   
        public Bitmap CaptureImage(Image img, int width, int height, int spaceX, int spaceY)
        {
            //载入底图   
            //Image fromImage = Image.FromFile(sFromFilePath);
            Image fromImage = img;
            int x = 0;   //截取X坐标   
            int y = 0;   //截取Y坐标   
            //原图宽与生成图片宽   之差       
            //当小于0(即原图宽小于要生成的图)时，新图宽度为较小者   即原图宽度   X坐标则为0     
            //当大于0(即原图宽大于要生成的图)时，新图宽度为设置值   即width         X坐标则为   sX与spaceX之间较小者   
            //Y方向同理   
            int sX = fromImage.Width - width;
            int sY = fromImage.Height - height;
            if (sX > 0)
            {
                x = sX > spaceX ? spaceX : sX;
            }
            else
            {
                width = fromImage.Width;
            }
            if (sY > 0)
            {
                y = sY > spaceY ? spaceY : sY;
            }
            else
            {
                height = fromImage.Height;
            }

            //创建新图位图   
            Bitmap bitmap = new Bitmap(width, height);
            //创建作图区域   
            Graphics graphic = Graphics.FromImage(bitmap);
            //截取原图相应区域写入作图区   
            graphic.DrawImage(fromImage, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
            //从作图区生成新图   
            //Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
            // Bitmap saveImage = GetThumbnail(Image.FromHbitmap(bitmap.GetHbitmap()), height-10, width);
            Bitmap saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
            //bitmap.Dispose();
            //graphic.Dispose();
            GC.Collect();
            return saveImage;
            //保存图象   
            //saveImage.Save(saveFilePath, ImageFormat.Jpeg);
            ////释放资源   
            //saveImage.Dispose();
            //bitmap.Dispose();
            //graphic.Dispose();
        }
        #endregion


        /// <SUMMARY>
        /// 图片缩放
        /// </SUMMARY>
        /// <PARAM name="sourceFile">图片源路径</PARAM>
        /// <PARAM name="destFile">缩放后图片输出路径</PARAM>
        /// <PARAM name="destHeight">缩放后图片高度</PARAM>
        /// <PARAM name="destWidth">缩放后图片宽度</PARAM>
        /// <RETURNS></RETURNS>
        public static Bitmap GetThumbnail(Image img, int destHeight, int destWidth)
        {
            System.Drawing.Image imgSource = img;
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            int sW = 0, sH = 0;
            // 按比例缩放
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;

            if (sHeight > destHeight || sWidth > destWidth)
            {
                if ((sWidth * destHeight) > (sHeight * destWidth))
                {
                    sW = destWidth;
                    sH = (destWidth * sHeight) / sWidth;
                }
                else
                {
                    sH = destHeight;
                    sW = (sWidth * destHeight) / sHeight;
                }
            }
            else
            {
                sW = sWidth;
                sH = sHeight;
            }

            Bitmap outBmp = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.WhiteSmoke);

            // 设置画布的描绘质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();

            // 以下代码为保存图片时，设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;
            return outBmp;
        }

        public MethodInfo GetScriptMethod(string strMethodName)
        {
            if (this.myInfo.EnableScript && (this.myZYVBEngine != null))
            {
                if (this.myScript.ScriptModified)
                {
                    this.StartScript();
                    this.myScript.ScriptModified = false;
                }
                return this.myZYVBEngine.GetScriptMethod(strMethodName);
            }
            return null;
        }

        public string GetValue(string strName)
        {
            return this.myVariables.GetValue(strName);
        }

        public bool HandleCommnad(string CommandName, string Param1, string Param2, string Param3)
        {
            foreach (A_Action action in this.myActions)
            {
                if ((action.ActionName() == CommandName) && action.isEnable())
                {
                    action.Param1 = Param1;
                    action.Param2 = Param2;
                    action.Param3 = Param3;
                    return action.UIExecute();
                }
            }
            return false;
        }

        public void HideCaret()
        {
            if (this.myOwnerControl != null)
            {
                this.myOwnerControl.HideOwnerCaret();
            }
        }

        public int IndexOf(ZYTextElement myElement)
        {
            return this.myElements.IndexOf(myElement);
        }

        /// <summary>
        /// 初始化编辑区域的动作
        /// </summary>
        private void InitActionList()
        {
            this.myActions.Clear();
            this.myActions.Add(new A_Enter());
            this.myActions.Add(new A_InsertChar());
            this.myActions.Add(new A_InsertImage());
            this.myActions.Add(new A_BackSpace());
            this.myActions.Add(new A_Copy());
            this.myActions.Add(new A_Cut());
            this.myActions.Add(new A_Delete());
            this.myActions.Add(new A_FontName());
            this.myActions.Add(new A_FontSize());
            this.myActions.Add(new A_DeleteFormat());
            this.myActions.Add(new A_FontBold());
            this.myActions.Add(new A_ToXBS());
            this.myActions.Add(new A_FontItalic());
            this.myActions.Add(new A_Zoom());
            this.myActions.Add(new A_InsertDiagnose());
            this.myActions.Add(new A_printdocument());
            this.myActions.Add(new A_FontUnderline());
            this.myActions.Add(new A_InsertPacs());
            this.myActions.Add(new A_MoveDown());
            this.myActions.Add(new A_MoveLeft());
            this.myActions.Add(new A_Undo());
            this.myActions.Add(new A_Redo());
            this.myActions.Add(new A_MoveRight());
            this.myActions.Add(new A_MoveUp());
            this.myActions.Add(new A_PageDown());
            this.myActions.Add(new A_PageUp());
            this.myActions.Add(new A_InsertLisCheckoutAndCheck());
            this.myActions.Add(new A_Paste());
            this.myActions.Add(new A_InsertTheSignature());
            this.myActions.Add(new A_SetForeColor());
            this.myActions.Add(new A_CheckWords());
            this.myActions.Add(new A_SetSub());
            this.myActions.Add(new A_SetSup());
            this.myActions.Add(new A_CtlMoveDown());
            this.myActions.Add(new A_CtlMoveUp());
            this.myActions.Add(new A_ShiftMoveDown());
            this.myActions.Add(new A_ShiftMoveLeft());
            this.myActions.Add(new A_TableCellAlignBottom());
            this.myActions.Add(new A_TableCellAlignCenter());
            this.myActions.Add(new A_TableCellAlignTop());
            this.myActions.Add(new A_InsertDiv());
            this.myActions.Add(new A_ShiftMoveRight());
            this.myActions.Add(new A_ShiftMoveUp());
            this.myActions.Add(new A_ShiftPageDown());
            this.myActions.Add(new A_InsertNumInput());
            this.myActions.Add(new A_ShiftPageUp());
            this.myActions.Add(new A_MoveHome());
            this.myActions.Add(new A_ShiftMoveHome());
            this.myActions.Add(new A_MoveEnd());
            this.myActions.Add(new A_ShiftMoveEnd());
            this.myActions.Add(new A_InsertCheckBox());
            this.myActions.Add(new A_InsertMedia());
            this.myActions.Add(new A_FindOrReplace());
            this.myActions.Add(new A_InsertXML());
            this.myActions.Add(new A_InsertSelect());
            this.myActions.Add(new A_InsertMultipleSelect());
            this.myActions.Add(new A_InsertTemplate());
            this.myActions.Add(new A_InsertKeyWord());
            this.myActions.Add(new A_InsertString());
            this.myActions.Add(new A_InsertDoctorAdvice());
            this.myActions.Add(new A_TextTime());
            this.myActions.Add(new A_TableLock());
            this.myActions.Add(new A_InsertDocument());
            this.myActions.Add(new A_InsertInput());
            this.myActions.Add(new A_InsertSign());
            this.myActions.Add(new A_InsertExDataInput());
            this.myActions.Add(new A_InsertKB());
            this.myActions.Add(new A_InsertLine());
            this.myActions.Add(new A_InsertTable());
            this.myActions.Add(new A_InsertTableRowBelow());
            this.myActions.Add(new A_InsertTableRowAbove());
            this.myActions.Add(new A_CtrlTabToInput());
            this.myActions.Add(new A_InsertTableColLeft());
            this.myActions.Add(new A_InsertTableColRight());
            this.myActions.Add(new A_MergeTableCell());
            this.myActions.Add(new A_DeleteTableRow());
            this.myActions.Add(new A_DeleteTableCol());
            this.myActions.Add(new A_DeleteTable());
            this.myActions.Add(new A_VisibleTableBorder());
            this.myActions.Add(new A_SelectAll());
            this.myActions.Add(new A_SaveAs());
            this.myActions.Add(new A_InsertSuperiorSignature());
            this.myActions.Add(new A_SaveFile());
            this.myActions.Add(new A_SaveImage());
            this.myActions.Add(new A_Find());
            this.myActions.Add(new A_Replace());
            this.myActions.Add(new A_lockCell());
            this.myActions.Add(new A_ReplaceAll());
            this.myActions.Add(new A_InsertSurgery());
            this.myActions.Add(new A_Open());
            this.myActions.Add(new A_LogicDelete());
            this.myActions.Add(new A_ShowAll());
            this.myActions.Add(new A_RegisteUser());
            this.myActions.Add(new A_SetVariable());
            this.myActions.Add(new A_RemoveVariable());
            this.myActions.Add(new A_ViewSource());
            this.myActions.Add(new A_ViewDataSource());
            this.myActions.Add(new A_ViewStructSource());
            this.myActions.Add(new A_LockDocument());
            this.myActions.Add(new A_AlignCenter());
            this.myActions.Add(new A_AlignLeft());
            this.myActions.Add(new A_AlignRight());
            this.myActions.Add(new A_AlignJustify());
            this.myActions.Add(new A_AlignTCCenter());
            this.myActions.Add(new A_DocumentTitle());
            this.myActions.Add(new A_SaveTemplate());
            this.myActions.Add(new A_NewFile());
            this.myActions.Add(new A_OpenDBFile());
            this.myActions.Add(new A_SaveDBFile());
            this.myActions.Add(new A_InsertTubeBedSign());
            this.myActions.Add(new A_FieldName());
            this.myActions.Add(new A_TableRowHeight());
            this.myActions.Add(new A_SetUserLevel());
            this.myActions.Add(new A_ShowMark());
            this.myActions.Add(new A_SetFont());
            this.myActions.Add(new A_InsertSignature());
            this.myActions.Add(new A_PageViewMode());
            this.myActions.Add(new A_SetPageSettings());
            this.myActions.Add(new A_ShowParagraphFlag());
            this.myActions.Add(new A_AboutMe());
            this.myActions.Add(new A_ConvertTextToSelect());
            this.myActions.Add(new A_SetInputFormat());
            this.myActions.Add(new A_SetMultiSelect());
            this.myActions.Add(new A_DivProperty());
            this.myActions.Add(new A_DesignMode());
            this.myActions.Add(new A_UnderWriteMark());
            this.myActions.Add(new A_UnderWriteMarkUI());
            this.myActions.Add(new A_SetBackColor());
            this.myActions.Add(new A_ClearSaveLog());
            this.myActions.Add(new A_ActiveSmartTag());
            this.myActions.Add(new A_EnableSmartTag());
            this.myActions.Add(new A_OwnerSection());
            this.myActions.Add(new A_SectionSQL());
            this.myActions.Add(new A_ContentChanged());
            this.myActions.Add(new A_EditScript());
            this.myActions.Add(new A_EnableKBSection());
            this.myActions.Add(new A_ErrorReportURL());
            this.myActions.Add(new 等等());
            this.myActions.Add(new A_SetTextName());
            this.myActions.Add(new A_SetPageSize());
            this.myActions.Add(new A_SetPageMargins());
            this.myActions.Add(new A_RemoveBlankLine());
            this.myActions.Add(new A_SetDefaultFont());
            this.myActions.Add(new A_InsertFixedInput());
            this.myActions.Add(new A_EnableJumpPrint());
            this.myActions.Add(new A_PrintView());
            this.myActions.Add(new A_FormatAll());
            this.myActions.Add(new A_Out());
            this.myActions.Add(new A_In());
            this.myActions.Add(new A_SetLineSpacing());
            this.myActions.Add(new A_InsertMedicine());
            this.myActions.Add(new A_InsertGongshi());
            this.myActions.Add(new A_InsertRadiobutton());
            this.myActions.Add(new A_InsertKnowledge());
            this.myActions.Add(new A_SetHeadInfo());
            this.myActions.Add(new A_SaveDB());
            foreach (A_Action action in this.myActions)
            {
                action.OwnerDocument = this;
            }
        }

        public bool InitZYVBEngine()
        {
            try
            {
                this.myZYVBEngine = new ZYVBScriptEngine();
                this.myZYVBEngine.OwnerDocument = this;
                return true;
            }
            catch (Exception exception)
            {
                ZYErrorReport.Instance.SourceException = exception;
                ZYErrorReport.Instance.SourceObject = this;
                ZYErrorReport.Instance.UserMessage = "初始化ZYVB脚本引擎错误";
                ZYErrorReport.Instance.MemberName = "ZYTextDocument.InitZYVBEngine";
                ZYErrorReport.Instance.ReportError();
            }
            return false;
        }

        public void InitEventObject(ZYVBEventType EventType)
        {
            if (this.myInfo.EnableScript && (this.myZYVBEngine != null))
            {
                this.myZYVBEngine.EventObj.EventType = EventType;
                if (this.myOwnerControl != null)
                {
                    this.myOwnerControl.InitEventObject(this.myZYVBEngine.EventObj);
                }
            }
        }

        private void InnerDefineField(string strName, TypeBuilder tb, Hashtable myNames, object obj)
        {
            strName = strName.Trim().ToLower();
            if (StringCommon.HasContent(strName) && !myNames.ContainsKey(strName))
            {
                myNames.Add(strName, obj);
                tb.DefineField(strName, typeof(object), FieldAttributes.Public);
            }
        }

        public bool InsertByXML(string strXML)
        {
            if (this.Locked)
            {
                return false;
            }
            XmlDocument document = new XmlDocument();
            document.LoadXml(strXML);
            ZYTextElement newElement = this.CreateElementByXML(document.DocumentElement);
            if (newElement != null)
            {
                this.myContent.InsertElement(newElement);
            }
            return true;
        }

        public bool InTable(ZYTextContainer container, int x, int y, ref ZYTextTable ownerTable)
        {
            foreach (ZYTextElement element in container.ChildElements)
            {
                if (element.Bounds.Contains(x, y))
                {
                    if (element is ZYTextTable)
                    {
                        ownerTable = (ZYTextTable)element;
                        return true;
                    }
                    if (element is ZYTextContainer)
                    {
                        return this.InTable((ZYTextContainer)element, x, y, ref ownerTable);
                    }
                }
            }
            return false;
        }

        public object InvokeScriptMethod(string strMethodName, object obj, object[] Parameters)
        {
            if (this.myInfo.EnableScript && (this.myZYVBEngine != null))
            {
                if (this.myScript.ScriptModified)
                {
                    this.StartScript();
                    this.myScript.ScriptModified = false;
                }
                this.myZYVBEngine.HasUserInterface = false;
                object obj2 = this.myZYVBEngine.InvokeScriptMethod(strMethodName, obj, Parameters);
                if (this.myZYVBEngine.HasUserInterface && (this.myOwnerControl != null))
                {
                    this.myOwnerControl.Refresh();
                }
                return obj2;
            }
            return null;
        }

        /// <summary>
        /// 删除编辑区域中的元素
        /// </summary>
        /// <param name="myElement"></param>
        /// <returns></returns>
        public int isDeleteElement(ZYTextElement myElement)
        {
            this.InitEventObject(ZYVBEventType.BeforeDelete);
            this.EventObj.Element = myElement;
            ZYTextTable zt = this.GetInTable(myElement);

            if (zt != null && !(myElement is ZYTextTable))
            {
                if (myElement.RealTop < zt.RealTop)
                {
                    return 1;
                }
            }
            if (myElement == myElement.Parent.vLastElement)
            {
                return 1;
            }
            if (this.myInfo.LogicDelete)
            {
                myElement.Deleteted = true;
                if (this.myOwnerControl != null)
                {
                    this.myOwnerControl.AddInvalidateRect(myElement.Bounds);
                }
                return 2;
            }
            return 0;
        }

        /// <summary>
        /// 判断是否是"span", "div", "image"元素名
        /// </summary>
        /// <param name="strName"></param>
        /// <returns></returns>
        public static bool isElementXMLName(string strName)
        {
            string[] strArray = new string[] { "span", "div", "image" };
            for (int i = 0; i < strArray.Length; i++)
            {
                if (strArray[i].Equals(strName))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 是否取药重画区域
        /// </summary>
        /// <param name="myElement"></param>
        /// <returns></returns>
        public bool isNeedDraw(ZYTextElement myElement)
        {
            if (myElement == null)
            {
                return false;
            }
            return this.myView.isNeedDraw(myElement.RealLeft, myElement.RealTop, myElement.Width, myElement.Height);
        }

        /// <summary>
        /// 是否需要重画元素
        /// </summary>
        /// <param name="myRect"></param>
        /// <returns></returns>
        public bool isNeedDraw(Rectangle myRect)
        {
            return this.myView.isNeedDraw(myRect);
        }

        public bool isNeedDraw(int vLeft, int vTop, int vWidth, int vHeight)
        {
            return this.myView.isNeedDraw(vLeft, vTop, vWidth, vHeight);
        }

        /// <summary>
        /// 判断是否被选中
        /// </summary>
        /// <param name="myElement"></param>
        /// <returns></returns>
        public bool isSelected(ZYTextElement myElement)
        {
            if (this.isDrawBack || (myElement == null))
            {
                return false;
            }
            return (((myElement.Parent is ZYTextTableCell) && this.myContent.isSelected(myElement)) || (this.myContent.isSelected(myElement) || ((myElement.Parent is ZYTextBlock) && this.myContent.isSelected(myElement.Parent))));
        }

        /// <summary>
        /// 判断是否可见
        /// </summary>
        /// <param name="myElement"></param>
        /// <returns></returns>
        public bool isVisible(ZYTextElement myElement)
        {
            //if (myElement.CreatorIndex == -1)
            //{
            //    return true;
            //}
            if (this.myInfo.VisibleUserLevel >= 0)
            {
                if (myElement.CreatorIndex > this.myInfo.VisibleUserLevel)
                {
                    return false;
                }
                if (myElement.DeleterIndex > this.myInfo.VisibleUserLevel)
                {
                    return true;
                }
            }
            if (myElement is ZYTextDiv)
            {
                ZYTextDiv div = (ZYTextDiv)myElement;
                if (this.Info.Printing)
                {
                    if (div.ChildElements.Count > 0 && div.ChildElements[0] is ZYTextDiv)
                    {
                        ZYTextDiv div2 = div.ChildElements[0] as ZYTextDiv;
                        if (div2.Title.Contains("诊断") && div2.ChildElements.Count < 2)
                        {
                            return false;
                        }
                    }
                    else if ((div.Title.Contains("诊断")) && div.ChildElements.Count < 2)
                    {
                        return false;
                    }
                }
                if (!div.Deleteted && this.Us.InpatientInfo != null)
                {
                    return !div.Visible;
                }
            }
            return (this.myInfo.ShowAll || !myElement.Deleteted);
        }

        public bool isDiagnoseName(string title)
        {
            if (title.Contains("术前诊断") ||
                title.Contains("术后诊断") ||
                title.Contains("初步诊断") ||
                title.Contains("补充诊断") ||
                title.Contains("修正诊断") ||
                title.Contains("修订诊断") ||
                title.Contains("出院诊断") ||
                title.Contains("死亡诊断") ||
                title.Contains("入院诊断"))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 将某XML节点下的子节点插入列表中
        /// </summary>
        /// <param name="myElement">当前xml节点</param>
        /// <param name="myList">列表</param>
        /// <returns></returns>
        public bool LoadElementsToList(XmlElement myElement, ArrayList myList)
        {
            ZYTextElement element = null;
            foreach (XmlNode node in myElement.ChildNodes)
            {
                if ((node.Name == "#text") || (node.Name == "span"))
                {
                    string innerText = node.InnerText;
                    if ((innerText != null) && (innerText.Length > 0))
                    {
                        innerText = HttpUtility.HtmlDecode(innerText).Replace("\r", "").Replace("\n", "");
                        int textLength = innerText.Length;
                        if (textLength > 0)
                        {
                            ZYTextChar ch2 = null;
                            if (node is XmlElement)
                            {
                                ZYTextChar ch = ZYTextChar.Create(' ');
                                myList.Add(ch);
                                ch.OwnerDocument = this;
                                ch.FromXML(node as XmlElement);
                                for (int i = 1; i < textLength; i++)
                                {
                                    ch2 = ZYTextChar.Create(innerText[i]);
                                    ch.Attributes.CopyTo(ch2.Attributes);
                                    ch2.UpdateAttrubute();
                                    ch2.CreatorIndex = ch.CreatorIndex;
                                    ch2.DeleterIndex = ch.DeleterIndex;
                                    myList.Add(ch2);
                                }
                            }
                            else
                            {
                                for (int i = 0; i < textLength; i++)
                                {
                                    ch2 = this.CreateChar(innerText[i]);
                                    ch2.ForeColor = Color.Black;
                                    ch2.OperaterCreater = "0";
                                    ch2.CreatorIndex = 0;
                                    ch2.DeleterIndex = -1;
                                    myList.Add(ch2);
                                }
                            }
                        }
                    }
                    continue;
                }
                XmlElement element2 = node as XmlElement;
                if (element2 != null)
                {
                    element = this.CreateElement(element2.Name);
                    if ((element != null) && element.FromXML(element2))
                    {
                        myList.Add(element);
                    }
                }
            }
            foreach (ZYTextElement element3 in myList)
            {
                element3.OwnerDocument = this;
            }
            return true;
        }




        /// <summary>
        /// 加载文本元素列表
        /// </summary>
        /// <param name="strText"></param>
        /// <param name="myList"></param>
        /// <returns></returns>
        public int LoadTextElementsToList(string strText, ArrayList myList)
        {
            int num = 0;
            if ((strText == null) || (myList == null))
            {
                return -1;
            }
            foreach (char ch in strText)
            {
                if (ch == '\n')
                {
                    myList.Add(new ZYTextParagraph());
                    num++;
                }
                else if (ch != '\r')
                {
                    myList.Add(this.CreateChar(ch));
                    num++;
                }
            }
            return num;
        }

        /// <summary>
        /// 刷新
        /// </summary>
        public void Refresh()
        {
            if (this.myOwnerControl != null)
            {
                this.myOwnerControl.Refresh();
            }
        }

        /// <summary>
        /// 刷新元素
        /// </summary>
        /// <param name="myElement"></param>
        public void RefreshElement(ZYTextElement myElement)
        {
            if (this.myOwnerControl != null)
            {
                if (myElement is ZYTextContainer)
                {
                    this.myOwnerControl.AddInvalidateRect((myElement as ZYTextContainer).GetContentBounds());
                }
                else
                {
                    this.myOwnerControl.AddInvalidateRect(myElement.Bounds.Left, myElement.OwnerLine.RealTop, myElement.Width + myElement.WidthFix, myElement.OwnerLine.Height);
                }
                this.myOwnerControl.Refresh();
            }
        }

        public void RefreshElements()
        {
            this.myElements.Clear();
            if (this.myDocumentElement != null)
            {
                this.myDocumentElement.AddElementToList(this.myElements, true);
                int num = 0;
                foreach (ZYTextElement element in this.myElements)
                {
                    element.Index = num;
                    num++;
                    element.Visible = true;
                    string ii = element.OperaterCreater;
                    element.OperaterCreater = ii;

                    if ((element.CreatorIndex > 0) && (this.Info.ShowAll))
                    {
                        element.ForeColor = System.Drawing.Color.Green;
                    }
                    else if ((Convert.ToInt16(element.OperaterCreater) > 0) && (this.Info.ShowAll))
                    {
                        element.ForeColor = System.Drawing.Color.Green;
                    }
                    else
                    {
                        element.ForeColor = element.TempForeColor;
                    }
                }
            }
            this.myContent.AutoClearSelection = true;
            this.myContent.MoveSelectStart(this.myContent.SelectStart);
            this.myContainters.Clear();
            this.SetContainers(this.myDocumentElement);
            this.myAllElement = null;
        }

        public void RefreshElementsOne()
        {
            this.myElements.Clear();
            if (this.myDocumentElement != null)
            {
                this.myDocumentElement.AddElementToList(this.myElements, true);
                int num = 0;
                foreach (ZYTextElement element in this.myElements)
                {
                    element.Visible = true;
                    string ii = element.OperaterCreater;
                    element.OperaterCreater = ii;
                    element.TempForeColor = element.ForeColor;
                    element.Index = num;
                    num++;
                }
            }
            this.myContent.AutoClearSelection = true;
            this.myContent.MoveSelectStart(this.myContent.SelectStart);
            this.myContainters.Clear();
            this.SetContainers(this.myDocumentElement);
            this.myAllElement = null;
        }


        /// <summary>
        /// 是否启用续打
        /// </summary>
        public bool EnableJumpPrint
        {
            get
            {
                return this.bolEnableJumpPrint;
            }
            set
            {
                this.bolEnableJumpPrint = value;
            }
        }

        /// <summary>
        /// 初始化或编辑时创建或更新行（页面由行组成）
        /// </summary>
        /// <returns></returns>
        public bool RefreshLine()
        {
            this.myLines.Clear();
            if (this.myDocumentElement != null)
            {
                this.myDocumentElement.RefreshLine();
                this.RefreshPages();
                this.Menus.UpdateAction();
            }
            return true;
        }

        private void RefreshSection()
        {
            List<ZYTextSplit> splitList = GetSplitList();
            if (splitList != null)
            {
                ArrayList list = new ArrayList();
                PrintPage page = null;
                foreach (PrintPage printpage in this.myPages.Items)
                {
                    foreach (ZYTextSplit splitElement in splitList)
                    {
                        if (printpage.Section_name == "")
                        {
                            if (printpage.Bounds.Contains(splitElement.RealLeft, splitElement.RealTop) || splitElement.RealTop > printpage.Bounds.Y)
                            {
                                printpage.Section_name = splitElement.Section_name;
                                printpage.Bed_no = splitElement.Bed_no;
                                printpage.Sick_area = splitElement.Sick_area;
                                page = printpage;
                                break;
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(printpage.Section_name))
                    {
                        printpage.Section_name = splitList[splitList.Count - 1].Section_name;
                        if (printpage.Section_name == "" && this.Us.InpatientInfo != null)
                        {
                            printpage.Section_name = this.Us.InpatientInfo.Section_Name;
                            printpage.Bed_no = this.Us.InpatientInfo.Sick_Bed_Name;
                            printpage.Sick_area = this.Us.InpatientInfo.Sick_Area_Name;
                        }
                    }
                }
            }
        }

        public List<ZYTextSplit> GetSplitList()
        {
            List<ZYTextSplit> SplitList = new List<ZYTextSplit>();
            foreach (ZYTextElement element in this.Elements)
            {
                if (element is ZYTextSplit)
                    SplitList.Add((ZYTextSplit)element);
            }
            if (SplitList.Count < 1)
                return null;
            return SplitList;
        }

        ///<summary>
        ///更新页面
        ///</summary>
        public void RefreshPages()
        {
            this.myPages.Clear();
            this.myPages.DocumentHeight = this.myDocumentElement.Height;
            this.myPages.HeadHeight = this.HeadHeight;
            this.myPages.FooterHeight = this.FooterHeight;
            this.myPages.Top = 0;
            int BodyHeight = this.myDocumentElement.Height;
            int LastPos = this.myPages.Top;
            //int minPageHeight = 28;
            List<ZYTextLine> lines = new List<ZYTextLine>();
            int linesCount = this.myLines.Count;
            int forNowIndex = 0;
            int count = 0;
            while (((this.myPages.BodyHeight + this.myPages.HeadHeight) + this.myPages.TailHeight) < this.myDocumentElement.Height + this.DocumentElement.Top)
            {
                count++;
                PrintPage myPage = this.myPages.NewPage();

                int bottom = myPage.Bottom;
                ZYTextLine line = null;
                bool isSkip = false;
                for (int i = forNowIndex; i < linesCount; i++)
                {
                    ZYTextLine line2 = (ZYTextLine)this.myLines[i];
                    ZYTextElement lineFirstElement = (ZYTextElement)line2.Elements[0];

                    if (line2.IsSkip && line == null)
                    {
                        line = line2;
                        isSkip = true;
                        break;
                    }

                    if (lineFirstElement is ZYTextTable || lineFirstElement is ZYTextTableRow || lineFirstElement is ZYTextTableCell)
                    {
                        continue;
                    }

                    if (line != null)
                    {
                        if ((line2.Container is ZYTextTableCell) && line2.Container.Parent == line.Container.Parent)
                        {
                            if ((line2.RealTop + line2.FullHeight) > bottom && line2.FullHeight > line.FullHeight && bottom >= line2.RealTop)
                            {
                                line = line2;
                            }
                            continue;
                        }
                        else
                        {
                            if (line2.RealTop > bottom)
                            {
                                break;
                            }
                            if (lineFirstElement is ZYTextDiv)
                            {
                                int height = line2.RealTop + line2.FullHeight >= myPage.Bottom ? line2.RealTop : line2.RealTop + line2.FullHeight;// (line.RealTop + line.FullHeight) - myPage.Bottom;
                                int height2 = myPage.Bottom - height;
                                if (height2 > 0 && height2 < 28)
                                {
                                    line = line2;
                                    break;
                                }
                            }
                        }
                    }

                    if (line2.RealTop + line2.FullHeight >= bottom && line == null && !(lineFirstElement is ZYTextDiv))
                    {
                        line = line2;
                        continue;
                    }
                }

                if (line != null)
                {

                    int titlesize = 0;
                    if (line.Container is ZYTextDiv)
                    {
                        ZYTextDiv d = (ZYTextDiv)line.Container;
                        if (d.Lines[0] == line && d.TitleLine)
                        {
                            titlesize = (int)d.TitleSize().Height;
                        }
                    }
                    if (isSkip)
                        myPage.Bottom = line.RealTop + line.FullHeight;
                    else
                    {
                        int s1 = (line.RealTop + line.FullHeight >= myPage.Bottom ? line.RealTop - (((line.Container is ZYTextTableCell) ? this.Info.LineSpacing / 2 : 0)) : line.RealTop + line.FullHeight);
                        if (titlesize > 0 && s1 >= myPage.Bottom)
                        {
                            s1 = s1 - titlesize;
                        }
                        myPage.Bottom = s1;
                    }
                    if (isSkip == false && line.IsSkip)
                    {
                        forNowIndex = this.myLines.IndexOf(line);
                    }
                    else
                    {
                        forNowIndex = this.myLines.IndexOf(line) + 1;
                    }
                    line = null;
                }
                else
                {
                    myPage.Bottom = this.myDocumentElement.Top + this.myDocumentElement.Height;
                }
                this.myPages.AddPage(myPage);
            }

            if ((this.myOwnerControl != null) && this.myOwnerControl.PageViewMode)
            {
                this.RefreshSection();
                this.myOwnerControl.RefreshPages();
            }
        }

        public bool visibleTextName = false;
        public bool VisibleTextName
        {
            get
            {
                return visibleTextName;
            }

            set
            {
                visibleTextName = value;
            }
        }
        /// <summary>
        /// 更新编辑区域的大小
        /// </summary>
        /// <returns></returns>
        public bool RefreshSize()
        {
            if (this.myDocumentElement != null)
            {
                this.myDocumentElement.Left = 0;
                this.myDocumentElement.Top = 0;
                this.myDocumentElement.RefreshSize();
                this.myDocumentElement.RefreshLine();
                this.myView.Height = this.myDocumentElement.Top + this.myDocumentElement.Height;
            }
            return true;
        }

        public bool isDrawHeader()
        {
            if (this.OnDrawPageHeader != null)
                return true;
            return false;
        }

        private string bed_name = "";
        public string Bed_name
        {
            get
            {
                return bed_name;
            }

            set
            {
                bed_name = value;
            }
        }

        public void OnDrawHeader(Graphics g, Rectangle rectangle, int pageIndex, PageHeaders header)
        {
            if (this.OnDrawPageHeader != null)
            {
                if (!string.IsNullOrEmpty(bed_name))
                {
                    header.Old_bed_name = this.bed_name;
                }
                if (!string.IsNullOrEmpty(section_name))
                {
                    header.Old_section_name = this.section_name;
                }
                if (!string.IsNullOrEmpty(area_name))
                {
                    header.Old_sick_area = this.area_name;
                }
                this.OnDrawPageHeader(g, rectangle, pageIndex, header, this);
            }
        }

        public void RegisterUndo(A_Action a)
        {
            if (((this.intUndoState == 0) && (a != null)) && a.isUndoable())
            {
                A_Action action = a.Clone();
                if (action != null)
                {
                    this.myUndoList.Add(action);
                    this.myRedoList.Clear();
                }
            }
        }
        public int JumpPrintPosition
        {
            get
            {
                return this.intJumpPrintPosition;
            }
            set
            {
                this.intJumpPrintPosition = value;
            }
        }

        private int HowElemetLine = 0;
        public int HowPrintPoint
        {
            get
            {
                return this.HowElemetLine;
            }
            set
            {
                this.HowElemetLine = value;
            }
        }

        private int printPageIndex = 0;

        public int PrintPageIndex
        {
            get { return printPageIndex; }
            set { printPageIndex = value; }
        }

        private int printPageTop = 0;

        public int PrintPageTop
        {
            get { return printPageTop; }
            set { printPageTop = value; }
        }

        //internal int FixPageLine(int Pos)
        //{
        //    PageLineInfo info = new PageLineInfo(0, 0, Pos, 0);
        //    this.FixPageLine(info);
        //    return info.Pos;
        //}

        //public void FixPageLine(PageLineInfo info)
        //{
        //    int pos = info.Pos;
        //    int min = 0x2710;
        //    ZYTextLine MinLine = null;
        //    foreach (ZYTextLine myLine in this.myLines)
        //    {
        //        int intRealTop = myLine.RealTop;
        //        if (((pos >= intRealTop) && ((pos - intRealTop) < min)) && (pos < (intRealTop + myLine.FullHeight)))
        //        {
        //            MinLine = myLine;
        //            min = pos - intRealTop;
        //        }
        //    }
        //    if (MinLine != null)
        //    {
        //        info.Pos = MinLine.RealTop;
        //    }
        //    else
        //    {
        //        info.Pos = this.myDocumentElement.Top + this.myDocumentElement.Height;
        //    }
        //}

        /// <summary>
        /// 删除空白字键域
        /// </summary>
        /// <param name="ContentLog"></param>
        /// <returns></returns>
        public int RemoveBlankKeyField(bool ContentLog)
        {
            int num = this.myDocumentElement.RemoveBlankKeyField2(ContentLog);
            if (num > 0)
            {
                this.Modified = true;
                this.RefreshElements();
                this.RefreshLine();
                this.UpdateView();
            }
            return num;
        }

        public int RemoveBlankLine()
        {
            int num = this.myDocumentElement.RemoveBlankLine();
            if (num > 0)
            {
                this.Modified = true;
                this.RefreshElements();
                this.RefreshLine();
                this.UpdateView();
            }
            return num;
        }

        public object RunEventScript(ZYTextContainer element, string strName)
        {
            if ((this.myInfo.EnableScript && (this.myZYVBEngine != null)) && ((element != null) && StringCommon.HasContent(strName)))
            {
                strName = strName.Trim();
                MethodInfo scriptMethod = this.GetScriptMethod(element.Name + "_" + strName);
                if (scriptMethod == null)
                {
                    scriptMethod = this.GetScriptMethod(element.ID + "_" + strName);
                }
                if (scriptMethod == null)
                {
                    return null;
                }
                this.myZYVBEngine.HasUserInterface = false;
                object obj2 = this.myZYVBEngine.InvokeScriptMethod(scriptMethod, null, null);
                if (this.myZYVBEngine.HasUserInterface && (this.myOwnerControl != null))
                {
                    this.myOwnerControl.Refresh();
                }
                return obj2;
            }
            return null;
        }

        /// <summary>
        /// 选择内容改变
        /// </summary>
        /// <param name="s1"></param>
        /// <param name="e1"></param>
        /// <param name="s2"></param>
        /// <param name="e2"></param>
        public void SelectionChanged(int s1, int e1, int s2, int e2)
        {
            try
            {
                if (this.myOwnerControl != null)
                {
                    this.OwnerControl.HideControls();
                    ZYTextElement element = null;
                    if ((((e1 == 0) && (e2 == 0)) && ((s1 != s2) && (s1 >= 0))) && (((s1 < this.myElements.Count) && (s2 >= 0)) && (s2 < this.myElements.Count)))
                    {
                        ZYTextElement myElement = (ZYTextElement)this.myElements[s1];
                        ZYTextElement element3 = (ZYTextElement)this.myElements[s2];
                        if ((this.OnJumpDiv != null) && (ZYTextDiv.GetOwnerDiv(myElement) != ZYTextDiv.GetOwnerDiv(element3)))
                        {
                            this.OnJumpDiv(ZYTextDiv.GetOwnerDiv(myElement), ZYTextDiv.GetOwnerDiv(element3));
                        }
                    }
                    if (s1 != s2)
                    {

                        for (int i = s1; i <= s2; i++)
                        {
                            element = (ZYTextElement)this.myElements[i];

                            if (element.OwnerLine == null)
                            {
                                continue;
                            }
                        }
                    }
                    if (e1 != e2)
                    {
                        for (int j = e1; j <= e2; j++)
                        {
                            element = (ZYTextElement)this.myElements[j];
                            if (element.OwnerLine == null)
                            {
                                continue;
                            }
                        }
                    }
                    //this.myOwnerControl.UpdateInvalidateRect();
                    this.myOwnerControl.UpdateTextCaret();
                    if (this.OnSelectionChanged != null)
                    {
                        this.OnSelectionChanged(this, null);
                    }
                }
                this.Menus.UpdateAction();
            }
            catch
            {

                throw;
            }
        }

        /// <summary>
        /// 编辑区域的对齐方式设置
        /// </summary>
        /// <param name="intAlign"></param>
        /// <returns></returns>
        public bool SetAlign(ParagraphAlignConst intAlign)
        {
            if (this.Locked)
            {
                return false;
            }
            bool flag = false;
            ArrayList selectParagraph = this.myContent.GetSelectParagraph();
            this.BeginContentChangeLog();
            foreach (ZYTextParagraph paragraph in selectParagraph)
            {
                if (paragraph.Align != intAlign)
                {
                    paragraph.Align = intAlign;
                    flag = true;
                }
            }
            this.myContentChangeLog.strUndoName = "设置对齐方式";
            this.EndContentChangeLog();
            if (flag)
            {
                this.RefreshLine();
                this.UpdateView();
                this.Refresh();
                this.myContent.Modified = true;
            }
            return flag;
        }

        /// <summary>
        /// 设置容器区域
        /// </summary>
        /// <param name="c"></param>
        private void SetContainers(ZYTextContainer c)
        {
            foreach (object obj2 in c.ChildElements)
            {
                if (obj2 is ZYTextContainer)
                {
                    this.myContainters.Add(obj2);
                    this.SetContainers(obj2 as ZYTextContainer);
                }
                if (obj2 is ZYTextObject)
                {
                    this.myContainters.Add(obj2);
                }
            }
        }

        /// <summary>
        /// 设置鼠标样式
        /// </summary>
        /// <param name="vCursor"></param>
        internal void SetCursor(Cursor vCursor)
        {
            if (this.OwnerControl.Cursor != vCursor)
                this.OwnerControl.Cursor = vCursor;
        }

        /// <summary>
        /// 设置字体类型
        /// </summary>
        /// <param name="NewFontName"></param>
        public void SetSelectioinFontName(string NewFontName)
        {
            this.SetSelectionAttribute(0, NewFontName);
        }

        /// <summary>
        /// 对选择区域进行相关的属性设置
        /// </summary>
        /// <param name="index"></param>
        /// <param name="strValue"></param>
        private void SetSelectionAttribute(int index, string strValue)
        {
            bool flag = false;
            if (!this.Locked)
            {
                ArrayList selectElements = this.myContent.GetSelectElements();
                ZYTextChar ch = null;
                ZYTextContainer parent = null;
                this.BeginContentChangeLog();
                for (int i = 0; i < selectElements.Count; i++)
                {
                    ch = selectElements[i] as ZYTextChar;
                    if (ch != null)
                    {
                        if ((parent != null) && (parent != ch.Parent))
                        {
                            parent.RefreshLine();
                        }
                        try
                        {
                            switch (index)
                            {
                                case 0:
                                    ch.FontName = strValue;
                                    break;
                                case 1:
                                    ch.FontSize = Convert.ToInt32(strValue);
                                    break;
                                case 2:
                                    ch.FontBold = strValue.Equals("1");
                                    break;
                                case 3:
                                    ch.FontItalic = strValue.Equals("1");
                                    break;
                                case 4:
                                    ch.FontUnderLine = strValue.Equals("1");
                                    break;
                                case 5:
                                    ch.ForeColor = Color.FromArgb(Convert.ToInt32(strValue));
                                    ch.TempForeColor = Color.FromArgb(Convert.ToInt32(strValue));
                                    break;
                                case 6:
                                    break;
                                case 7:
                                    ch.Sub = strValue.Equals("1");
                                    break;
                                case 8:
                                    ch.Sup = strValue.Equals("1");
                                    break;
                                case 9:
                                    ch.Font = this.View.DefaultFont;
                                    ch.Attributes.RemoveAttribute("fontname");
                                    ch.Attributes.RemoveAttribute("fontsize");
                                    break;

                                default:
                                    return;
                            }
                        }
                        catch (Exception)
                        {

                            throw;
                        }
                        ch.RefreshSize();
                        flag = true;
                    }
                }
                this.myContentChangeLog.strUndoName = "设置属性" + strValue;
                this.EndContentChangeLog();
                if (flag)
                {
                    this.RefreshLine();
                    this.UpdateView();
                    this.Refresh();
                    //this.ContentChanged();
                }
            }
        }

        /// <summary>
        /// 字体颜色
        /// </summary>
        /// <param name="NewColor"></param>
        public void SetSelectionColor(Color NewColor)
        {
            this.SetSelectionAttribute(5, NewColor.ToArgb().ToString());
        }

        /// <summary>
        /// 文字加粗
        /// </summary>
        /// <param name="NewBold"></param>
        public void SetSelectionFontBold(bool NewBold)
        {
            this.SetSelectionAttribute(2, NewBold ? "1" : "0");
        }

        /// <summary>
        /// 文字斜体
        /// </summary>
        /// <param name="NewItalic"></param>
        public void SetSelectionFontItalic(bool NewItalic)
        {
            this.SetSelectionAttribute(3, NewItalic ? "1" : "0");
        }

        /// <summary>
        /// 字体大小
        /// </summary>
        /// <param name="NewSize"></param>
        public void SetSelectionFontSize(int NewSize)
        {
            this.SetSelectionAttribute(1, NewSize.ToString());
        }

        /// <summary>
        /// 下标
        /// </summary>
        /// <param name="NewSub"></param>
        public void SetSelectionSub(bool NewSub)
        {
            this.SetSelectionAttribute(7, NewSub ? "1" : "0");
        }

        /// <summary>
        /// 上标
        /// </summary>
        /// <param name="NewSup"></param>
        public void SetSelectionSup(bool NewSup)
        {
            this.SetSelectionAttribute(8, NewSup ? "1" : "0");
        }

        /// <summary>
        /// 文字下划线
        /// </summary>
        /// <param name="UnderLine"></param>
        public void SetSelectionUnderLine(bool UnderLine)
        {
            this.SetSelectionAttribute(4, UnderLine ? "1" : "0");
        }

        /// <summary>
        /// 设置表格单元格对齐方式
        /// </summary>
        /// <param name="align"></param>
        /// <returns></returns>
        public bool SetTCAlign(TableCellAlign align)
        {
            if (this.Locked)
            {
                return false;
            }
            bool flag = false;
            this.BeginContentChangeLog();
            ZYTextTable inTable = this.GetInTable(this.myContent.CurrentElement);
            if ((inTable != null) && (inTable.SelectedCells.Count > 0))
            {
                foreach (ZYTextTableCell cell in inTable.SelectedCells)
                {
                    cell.Align = align;
                }
                flag = true;
            }
            if (!flag && (inTable != null))
            {
                ZYTextTableCell inTableCell = this.GetInTableCell(this.myContent.CurrentElement);
                if (inTableCell != null)
                {
                    inTableCell.Align = align;
                    flag = true;
                }
            }
            this.EndContentChangeLog();
            if (flag)
            {
                this.RefreshLine();
                this.UpdateView();
                this.Refresh();
                this.myContent.Modified = true;
            }
            return flag;
        }

        /// <summary>
        /// 设置图片信息消息提示框的内容，显示位置和大小
        /// </summary>
        /// <param name="strTip">内容</param>
        /// <param name="ImageIndex">图片索引</param>
        /// <param name="TipBounds">显示位置和大小</param>
        public void SetToolTip(string strTip, int ImageIndex, Rectangle TipBounds)
        {
            this.strToolTip = strTip;
            this.ToolTipImageIndex = ImageIndex;
            this.ToolTipBounds = TipBounds;
        }


        public void SetValue(string strName, string strValue)
        {
            this.myVariables.SetValue(strName, strValue);
        }

        public void setTime(ZYTextTime ze)
        {
            this.myOwnerControl.showTime(ze);
        }

        public void setMedicine(ZYTextMedicine ze)
        {
            this.myOwnerControl.showMedicine(ze);
        }

        public void SetSelectToList(ZYTextElement ze)
        {
            this.myOwnerControl.showKBList(ze);
        }

        public void SetInputTime(ZYTextInput _input)
        {
            this.myOwnerControl.showInputTime(_input);
        }

        /// <summary>
        /// 显示当前选中关键字的列表项
        /// </summary>
        /// <param name="myElement"></param>
        /// <returns></returns>
        public object ShowKBPopupList(ZYTextElement myElement)
        {
            if (!this.CheckKBLoaded())
            {
                this.LoadAllData();
            }
            object obj2 = this.myOwnerControl.ShowKBPopupList(myElement);
            if (this.myOwnerControl != null)
            {
                this.myOwnerControl.HideControls();
            }
            return obj2;
        }

        public int ShowPopupList(int x, int y, int height, object[] items, string strDefaultText)
        {
            if (!this.CheckKBLoaded())
            {
                return -1;
            }
            return this.myOwnerControl.ShowPopupList(x, y, height, items, strDefaultText);
        }

        public bool StartScript()
        {
            //if (this.myInfo.EnableScript && (this.myZYVBEngine != null))
            //{
            //    this.myZYVBEngine.ScriptText = this.myScript.RunTimeSourceCode;
            //    this.myZYVBEngine.OwnerDocument = this;
            //    return this.myZYVBEngine.StartScript();
            //}
            return false;
        }

        public void StopScript()
        {
            //if (this.myZYVBEngine != null)
            //{
            // this.myZYVBEngine.StopScript();
            //}
        }

        public bool ToXML(XmlElement RootElement)
        {
            if (RootElement == null)
            {
                return false;
            }
            RootElement.OwnerDocument.PreserveWhitespace = true;
            if (this.myInfo.SaveMode == 3)
            {
                if (this.myDocumentElement != null)
                {
                    this.myDocumentElement.ToXML(RootElement);
                }
            }
            else
            {
                RootElement.SetAttribute("version", "1.0");
                RootElement.SetAttribute("checkcount", this.myMarks.Count.ToString());
                RootElement.SetAttribute("senior", this.myMarks.LastSenior);
                //this.mySaveLogs.CurrentSaveLog.SaveDateTime = DateTime.Now;
                //********给当前日志设置IP值
                this.mySaveLogs.CurrentSaveLog.UserIP = this.GetUserIP();
                //**********
                //if (this.myMarks.NewMark != null)
                //{
                //    this.myMarks.NewMark.MarkTime = this.mySaveLogs.CurrentSaveLog.SaveDateTime;
                //    this.SaveLogs.CurrentSaveLog.UserName = this.Marks.NewMark.Senior;//如果是谁签名就在日志中username中显示签名人的名字则加上此行
                //}
                this.myMarks.ToXML(XMLCommon.CreateChildElement(RootElement, this.myMarks.GetXMLName(), true));
                this.mySaveLogs.ToXML(XMLCommon.CreateChildElement(RootElement, this.mySaveLogs.GetXMLName(), true));
                this.myInfo.ModifyTime = StringCommon.GetNowString14();
                this.myInfo.Version = "1.0";
                this.myInfo.ToXML(XMLCommon.CreateChildElement(RootElement, ZYDocumentInfo.GetXMLName(), true));
                if (this.myVariables.Count > 0)
                {
                    XmlElement element = XMLCommon.CreateChildElement(RootElement, "values", true);
                    for (int i = 0; i < this.myVariables.Count; i++)
                    {
                        XmlElement newChild = RootElement.OwnerDocument.CreateElement("value");
                        newChild.SetAttribute("name", this.myVariables.GetName(i));
                        newChild.InnerText = this.myVariables.GetValue(i);
                        element.AppendChild(newChild);
                    }
                }
                XmlElement pageElement = XMLCommon.CreateChildElement(RootElement, PrintPageCollection.GetXMLName(), true);
                this.Pages.ToXML(pageElement);
                this.myScript.ToXML(XMLCommon.CreateChildElement(RootElement, this.myScript.GetXMLName(), true));
                if (this.myInfo.SaveMode == 0)
                {
                    XmlElement element3 = XMLCommon.CreateChildElement(RootElement, "text", true);
                    StringBuilder myStr = new StringBuilder();
                    this.myDocumentElement.GetFinalText(myStr);
                    element3.InnerText = myStr.ToString();
                }

                XmlElement element4 = XMLCommon.CreateChildElement(RootElement, "head", true);
                this.Us.ToXML(element4);
                if (this.myDocumentElement != null)
                {
                    this.myDocumentElement.ToXML(XMLCommon.CreateChildElement(RootElement, "body", true));
                }
            }
            return true;
        }
        public bool IsHaveDeleted = false;

        /// <summary>
        /// 将编写的模板文件写入已有xml文件中
        /// </summary>
        /// <param name="myDoc"></param>
        /// <returns></returns>
        public bool ToXMLDocument(XmlDocument myDoc)
        {
            myDoc.PreserveWhitespace = true;
            myDoc.LoadXml("<emrtextdoc/>");
            return this.ToXML(myDoc.DocumentElement);
        }

        /// <summary>
        /// 将编写的模板写入新的xml文件中
        /// </summary>
        /// <param name="strURL">文件路径</param>
        /// <returns></returns>
        public bool ToXMLFile(string strURL)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml("<emrtextdoc/>");
            if (this.ToXML(document.DocumentElement))
            {
                document.Save(strURL);
                this.myInfo.FileName = strURL;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 保存模版的时候
        /// </summary>
        /// <returns></returns>
        public string GetDocXml()
        {
            XmlDocument document = new XmlDocument();
            document.PreserveWhitespace = true;
            document.LoadXml("<emrtextdoc/>");
            if (this.ToXML(document.DocumentElement))
            {
                if (this.isHaveTextId())
                {
                    XmlDocument newDocument = new XmlDocument();
                    newDocument.LoadXml("<emrtextdoc/>");
                    CreateNewXml(newDocument.DocumentElement, document.DocumentElement, 0);
                    return newDocument.OuterXml;
                }
                else
                {
                    XmlNodeList inputList = document.GetElementsByTagName("input");
                    foreach (XmlNode node in inputList)
                    {
                        if (node.Attributes["name"] != null)
                        {
                            string nodeName = node.Attributes["name"].Value;
                            if (nodeName == "上级医师职称")
                            {
                                node.InnerXml = "";
                                XmlNode xn = document.CreateElement("span");
                                xn.AppendChild(document.CreateTextNode("上级医师签名:"));
                                node.AppendChild(xn);
                            }
                            if (nodeName == "上级医师签名"
                              || nodeName == "普通医师签名"
                              || nodeName == "姓名"
                              || nodeName == "婚姻"
                              || nodeName == "职业"
                              || nodeName == "年龄"
                              || nodeName == "性别")
                            {
                                node.InnerXml = "";
                                node.Attributes["id"].Value = "";
                            }
                        }
                    }
                    return document.OuterXml;
                }
            }
            return "";
        }

        public void UpdateCaret()
        {

        }

        public void UpdateTextCaret()
        {
            if (this.myOwnerControl != null)
            {
                this.myOwnerControl.UpdateTextCaret();
            }
        }

        internal void UpdateUserName()
        {
            //if (this.myMarks.CanMark(this.mySaveLogs.CurrentUserName))
            //{
            //    this.bolLocked = false;
            //}
            //else
            //{
            //    this.bolLocked = this.myInfo.LockForMark;
            //}
            this.Refresh();
        }

        public void UpdateView()
        {
            if (this.UpdateViewNoScroll())
            {
                this.UpdateTextCaret();
            }
        }

        /// <summary>
        /// 判断模板页面是否已经超出指定范围，需要显示滚动条
        /// </summary>
        /// <returns></returns>
        public bool UpdateViewNoScroll()
        {
            if ((this.myOwnerControl != null) && this.myOwnerControl.CanUpdate())
            {
                if (!this.myOwnerControl.PageViewMode)
                {
                    this.myView.Height = (this.myDocumentElement.Top + this.myDocumentElement.Height) + 4;
                    if (!this.myOwnerControl.SetViewSize(this.myPages.StandardWidth, this.myView.Height))
                    {
                        this.myOwnerControl.UpdateInvalidateRect();
                    }
                }
                else
                {
                    this.myOwnerControl.RefreshPages();
                    this.myOwnerControl.UpdateInvalidateRect();
                }
                if (this.RefreshAllFlag)
                {
                    this.myOwnerControl.Refresh();
                    this.RefreshAllFlag = false;
                }
                return true;
            }
            return false;
        }

        public void UpdateViewSize()
        {
            this.myView.Width = this.myPages.StandardWidth;
        }

        public void ViewInsertModeChange()
        {
            ZYTextElement currentElement = this.myContent.CurrentElement;
            this.myOwnerControl.UpdateTextCaret();
        }

        internal int Calculate(string name)
        {
            List<ZYTextBlock> list = new List<ZYTextBlock>();
            string[] strs = name.Split('_');
            int sum = 0;
            string containtStr = "#" + strs[1];
            if (strs.Length > 1)
            {
                foreach (ZYTextElement element in this.Elements)
                {
                    if (element is ZYTextCheck)
                    {
                        ZYTextCheck block = ((ZYTextCheck)element);
                        if (block.Name.Contains(containtStr) && block.check == "Y")
                        {
                            string[] strNum = block.Name.Split('_');
                            if (strNum.Length > 1)
                            {
                                int isNum;
                                int.TryParse(strNum[strNum.Length - 1], out isNum);
                                if (isNum >= 0)
                                {
                                    sum += isNum;
                                }
                            }
                        }
                    }
                    else if (element is ZYTextInput)
                    {
                        ZYTextInput block = ((ZYTextInput)element);
                        if (block.ID.Contains(containtStr))
                        {
                            int isNum;
                            int.TryParse(block.Text, out isNum);
                            if (isNum >= 0)
                            {
                                sum += isNum;
                            }
                        }
                    }
                }
            }
            return sum;
        }

        /// <summary>
        /// 按下键盘时触发，判断是否用了快捷键
        /// </summary>
        /// <param name="KeyCode"></param>
        /// <param name="Alt"></param>
        /// <param name="Control"></param>
        /// <param name="Shift"></param>
        /// <returns></returns>
        public bool ViewKeyDown(Keys KeyCode, bool Alt, bool Control, bool Shift)
        {
            this.InitEventObject(ZYVBEventType.KeyDown);
            this.EventObj.KeyCode = (int)KeyCode;
            ZYTextElement currentElement = this.myContent.CurrentElement;
            foreach (A_Action action in this.myActions)
            {
                if ((action.isEnable() && action.CanHandleKeyDown()) && action.TestHotKey(KeyCode, Shift, Control, Alt))
                {
                    action.KeyCode = KeyCode;
                    action.ShiftKey = Shift;
                    action.ControlKey = Control;
                    action.AltKey = Alt;
                    action.Execute();
                    break;
                }
            }
            return true;
        }

        /// <summary>
        /// 松开按键以后
        /// </summary>
        /// <param name="KeyCode"></param>
        /// <param name="Alt"></param>
        /// <param name="Control"></param>
        /// <param name="Shift"></param>
        /// <returns></returns>
        public bool ViewKeyUp(Keys KeyCode, bool Alt, bool Control, bool Shift)
        {
            this.InitEventObject(ZYVBEventType.KeyUp);
            this.EventObj.KeyCode = (int)KeyCode;
            return true;
        }

        /// <summary>
        /// 鼠标在模板编辑区域单击时触发
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="Button"></param>
        /// <returns></returns>
        public bool ViewMouseClick(int x, int y, MouseButtons Button)
        {
            //新增当弹出药品选择框的时候用户点击编辑区域然后隐藏
            //if (this.SelectForm != null)
            //    SelectForm.Visible = false;
            this.InitEventObject(ZYVBEventType.Click);
            this.myDocumentElement.HandleClick(x, y, Button);
            this.OwnerControl.HideControls();
            return true;
        }

        /// <summary>
        /// 鼠标在模板编辑区域双击时触发
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="Button"></param>
        /// <returns></returns>
        public bool ViewMouseDoubleClick(int x, int y, MouseButtons Button)
        {
            this.InitEventObject(ZYVBEventType.DblClick);
            ZYTextElement current = this.myContent.CurrentElement;
            //List<ZYTextLine> list = new List<ZYTextLine>();
            //foreach (ZYTextLine line in this.Lines)
            //{
            //    if (y >= line.RealTop && y <= (line.RealTop + line.Height))
            //    {
            //        list.Add(line);
            //    }
            //}

            if (!this.myDocumentElement.HandleDblClick(x, y, Button)
                && ((current is ZYTextChar) || (this.myContent.PreElement is ZYTextChar))
                && !(current.Parent is ZYTextInput || current is ZYTextTime || current is ZYTextCheckBox
                || current is ZYTextCheck))
            {
                ZYTextChar ch;
                int num = -1;
                ZYTextContainer parent = this.myContent.CurrentElement.Parent;
                for (int i = (this.myContent.CurrentElement is ZYTextChar) ? this.myContent.SelectStart : (this.myContent.SelectStart - 1); i >= 0; i--)
                {
                    ch = this.myElements[i] as ZYTextChar;
                    if (((ch == null) || !char.IsLetter(ch.Char)) || (ch.Parent != parent))
                    {
                        break;
                    }
                    num = i;
                }
                if (num >= 0)
                {
                    for (int j = num; j < this.myElements.Count; j++)
                    {
                        ch = this.myElements[j] as ZYTextChar;
                        if ((ch == null) || !char.IsLetter(ch.Char))
                        {
                            this.myContent.SetSelection(j, num - j);
                            break;
                        }
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 鼠标离开编辑区域
        /// </summary>
        /// <returns></returns>
        public bool ViewMouseLeave()
        {
            this.InitEventObject(ZYVBEventType.MouseLeave);
            this.CurrentHoverElement = null;
            return true;
        }


        /// <summary>
        /// 鼠标右键按下操作
        /// </summary>
        /// <param name="x">x坐标</param>
        /// <param name="y">y坐标</param>
        /// <param name="Button">鼠标按下键</param>
        /// <returns>return</returns>
        public bool ViewMouseDown(int x, int y, MouseButtons Button)
        {
            this.InitEventObject(ZYVBEventType.MouseDown);
            if (Button == MouseButtons.Right)
            {
                if (this.myContent.SelectLength == 0)
                {
                    this.myContent.AutoClearSelection = true;
                    this.myContent.MoveTo(x, y);

                }
                return true;
            }
            if (((this.myDocumentElement != null) && (Button == MouseButtons.Left)) && this.myDocumentElement.HandleMouseDown(x, y, Button))
            {
                this.myOwnerControl.CaptureMouse = false;
                return true;
            }
            if (this.myContent.isDragMove)
            {

            }
            else
            {
                //if (Math.Abs(this.myContent.SelectLength) > 0 && isSelectElementNeedBound(x, y))
                //{
                //    this.myContent.isDragMove = true;
                //    this.SetCursor(Cursors.Hand);
                //    return true;
                //}
                //else
                //{
                //    this.myContent.AutoClearSelection = !this.myOwnerControl.HasShiftPressing();
                //}
            }
            this.myContent.AutoClearSelection = !this.myOwnerControl.HasShiftPressing();
            this.myOwnerControl.CaptureMouse = false;
            this.myContent.MoveTo(x, y);
            this.myOwnerControl.CaptureMouse = true;

            return true;
        }

        /// <summary>
        /// 元素是否在该集合内
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public bool isSelectElementNeedBound(int x, int y)
        {
            ArrayList selectElements = this.myContent.GetSelectElements();
            foreach (ZYTextElement var in selectElements)
            {
                if (var.Bounds.Contains(x, y))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 鼠标松开事件
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="Button"></param>
        /// <returns></returns>
        public bool ViewMouseUp(int x, int y, MouseButtons Button)
        {
            if (this.myContent.isDragMove)
            {
                ArrayList list = this.myContent.GetSelectElements();
                ZYTextElement.FixElementsForParent(list);
                ArrayList list2 = new ArrayList();
                if (list.Count > 0)
                {
                    this.myContent.MoveTo(x, y);
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.PreserveWhitespace = true;
                    xmlDocument.LoadXml("<emrDoc/>");
                    ZYTextElement.ElementsToXML(list, xmlDocument.DocumentElement);
                    string outXml = xmlDocument.OuterXml;
                    ZYTextElement currentElement = this.myContent.CurrentElement;
                    if (list.Contains(currentElement))
                    {
                        this.myContent.isDragMove = false;
                        return true;
                    }
                    foreach (ZYTextElement var in list)
                    {
                        if (var == var.Parent.GetLastElement())
                        {
                            continue;
                        }
                        var.Parent.ChildElements.Remove(var);
                    }
                    int InsertIndex = currentElement.Parent.ChildElements.IndexOf(currentElement);
                    xmlDocument.LoadXml(outXml);
                    this.LoadElementsToList(xmlDocument.DocumentElement, list2);
                    this.myContent.InsertRangeElements(list2);
                    this.myContent.isDragMove = false;
                    this.ContentChanged();
                }
                else
                {
                    this.myContent.isDragMove = false;
                }
            }
            this.InitEventObject(ZYVBEventType.MouseUp);
            return (((this.myDocumentElement != null) && this.myDocumentElement.HandleMouseUp(x, y, Button)) || true);
        }

        public ZYTextElement horeELement = null;
        /// <summary>
        /// 鼠标在编辑区域移动
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="Button"></param>
        /// <returns></returns>
        //public bool ViewMouseMove(int x, int y, MouseButtons Button)
        //{
        //    this.InitEventObject(ZYVBEventType.MouseMove);
        //    if (this.myContent.isDragMove)
        //    {
        //        foreach (ZYTextElement var in this.Elements)
        //        {
        //            if (var.Bounds.Contains(x, y))
        //            {
        //                horeELement = var;
        //                this.OwnerControl.UpdateTextCaret();
        //                return true;
        //            }
        //        }
        //        return true;
        //    }
        //    this.ToolTipImageIndex = -1;
        //    if (this.myOwnerControl.CaptureMouse)
        //    {
        //        if ((this.myDocumentElement != null) && this.myDocumentElement.HandleMouseMove(x, y, Button))
        //        {
        //            return true;
        //        }
        //        this.myContent.AutoClearSelection = false;
        //        this.myContent.MoveTo(x, y);
        //        this.myOwnerControl.UpdateTextCaret();
        //    }
        //    else
        //    {
        //        if (Button != MouseButtons.None)
        //        {
        //            return false;
        //        }
        //        this.strToolTip = "";
        //        ZYTextElement elementAt = this.myContent.GetElementAt(x, y);
        //        if (this.isSelected(elementAt) && !(elementAt is ZYTextObject))
        //        {
        //            this.SetCursor(Cursors.Default);
        //        }
        //        else
        //        {
        //            this.SetCursor(Cursors.IBeam);
        //            this.myDocumentElement.HandleMouseMove(x, y, Button);
        //            if ((this.myOwnerControl != null) && !this.myOwnerControl.StaticToolTip)
        //            {
        //                if (x > 0)
        //                    foreach (ZYTextElement element3 in this.myElements)
        //                    {
        //                        bool flag = false;
        //                        if (element3.Bounds.Contains(x, y) || ((element3 is ZYTextBlock) && (element3 as ZYTextContainer).Contains(x, y)))
        //                        {
        //                            string str = "";
        //                            if (this.mySaveLogs.IndexAvailable(element3.CreatorIndex))
        //                            {
        //                                ZYTextSaveLog log = this.mySaveLogs[element3.CreatorIndex];
        //                                str = log.UserName + " 于 " + log.DisplayDateTime + " 创建," + "IP：" + log.UserIP;
        //                                this.strToolTip = (this.strToolTip == null) ? str : (this.strToolTip + "\r\n" + str);
        //                                flag = true;
        //                            }
        //                            if (this.mySaveLogs.IndexAvailable(element3.DeleterIndex))
        //                            {
        //                                ZYTextSaveLog log2 = this.mySaveLogs[element3.DeleterIndex];
        //                                //str = log2.UserName + " 于 " + log2.DisplayDateTime + " 删除," + "IP：" + log2.UserIP;
        //                                if (!string.IsNullOrEmpty(str))
        //                                {
        //                                    str += "|";
        //                                }
        //                                str += log2.UserName + " 于 " + log2.DisplayDateTime + " 删除," + "IP：" + log2.UserIP;
        //                                this.strToolTip = (this.strToolTip == null) ? str : (this.strToolTip + "\r\n" + str);
        //                                flag = true;
        //                            }
        //                            if (flag)
        //                            {
        //                                this.OwnerControl.setToolTip("文字:", str, "", element3.Bounds, element3);
        //                                return true;
        //                            }
        //                            break;
        //                        }
        //                    }
        //            }
        //        }
        //        this.OwnerControl.HideToopTip();
        //    }
        //    return true;
        //}

        /// <summary>
        /// 判断按键是否与相关操作相关联
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        /// 

        public bool ViewMouseMove(int x, int y, MouseButtons Button)
        {
            this.InitEventObject(ZYVBEventType.MouseMove);
            if (this.myContent.isDragMove)
            {
                foreach (ZYTextElement var in this.Elements)
                {
                    if (var.Bounds.Contains(x, y))
                    {
                        horeELement = var;
                        this.OwnerControl.UpdateTextCaret();
                        return true;
                    }
                }
                return true;
            }
            this.ToolTipImageIndex = -1;
            if (this.myOwnerControl.CaptureMouse)
            {
                if ((this.myDocumentElement != null) && this.myDocumentElement.HandleMouseMove(x, y, Button))
                {
                    return true;
                }
                this.myContent.AutoClearSelection = false;
                //if (!this.AnRight)
                this.myContent.MoveTo(x, y);
                this.myOwnerControl.UpdateTextCaret();
            }
            else
            {
                if (Button != MouseButtons.None)
                {
                    return false;
                }
                this.strToolTip = "";
                ZYTextElement elementAt = this.myContent.GetElementAt(x, y);
                if (this.isSelected(elementAt) && !(elementAt is ZYTextObject))
                {
                    this.SetCursor(Cursors.Default);
                }
                else
                {
                    this.SetCursor(Cursors.IBeam);
                    this.myDocumentElement.HandleMouseMove(x, y, Button);
                    if ((this.myOwnerControl != null) && !this.myOwnerControl.StaticToolTip)
                    {
                        if (x > 0)
                            foreach (ZYTextElement element3 in this.myElements)
                            {
                                bool flag = false;
                                if (element3.Bounds.Contains(x, y) || ((element3 is ZYTextInput && ((ZYTextInput)element3).Name != null && ((ZYTextInput)element3).Name.Contains("签名")) && (element3 as ZYTextInput).Contains(x, y)))
                                {
                                    string str = "";
                                    if (this.mySaveLogs.IndexAvailable(element3.CreatorIndex))
                                    {
                                        ZYTextSaveLog log = this.mySaveLogs[element3.CreatorIndex];
                                        str = log.UserName + " 于 " + log.DisplayDateTime + " 创建," + "IP：" + log.UserIP;
                                        this.strToolTip = (this.strToolTip == null) ? str : (this.strToolTip + "\r\n" + str);
                                        flag = true;
                                    }

                                    if (element3.DeleterIndex >= 0)
                                    {
                                        ZYTextSaveLog log2 = this.mySaveLogs.GetSaveLog(element3.DeleterIndex);

                                        //str = log2.UserName + " 于 " + log2.DisplayDateTime + " 删除," + "IP：" + log2.UserIP;
                                        if (!string.IsNullOrEmpty(str))
                                        {
                                            str += "|";
                                        }
                                        str += log2.UserName + " 于 " + log2.DisplayDateTime + " 删除," + "IP：" + log2.UserIP;
                                        this.strToolTip = (this.strToolTip == null) ? str : (this.strToolTip + "\r\n" + str);
                                        flag = true;
                                    }
                                    if (flag)
                                    {
                                        this.OwnerControl.setToolTip("文字:", str, "", element3.Bounds, element3);
                                        return true;
                                    }
                                    break;
                                }
                            }
                    }
                }
                this.OwnerControl.HideToopTip();
            }
            return true;
        }

        public bool ViewNewChar(char c)
        {
            int num = c;
            bool flag = false;
            this.InitEventObject(ZYVBEventType.KeyPress);
            this.EventObj.KeyCode = num;
            foreach (A_Action action in this.myActions)
            {
                if ((action.isEnable() && !action.CanHandleKeyDown()) && action.TestHotKey((Keys)c, false, false, false))
                {
                    action.KeyCode = (Keys)c;
                    action.ShiftKey = false;
                    action.ControlKey = false;
                    action.AltKey = false;
                    flag = action.Execute();
                    break;
                }
            }
            return true;
        }

        public bool TestHotKey(Keys vKeyCode, bool vShift, bool vControl, bool vAlt)
        {
            if ((vShift || vControl) || vAlt)
            {
                return false;
            }
            char c = (char)((ushort)vKeyCode);
            if (char.IsControl(c))
            {
                return ((c == '\t') || (c == '\r'));
            }
            return true;
        }

        public bool ViewPaint(Graphics g, Rectangle ClipRect)
        {
            this.myView.ViewRect = ClipRect;
            Graphics innerGraph = this.myView.GetInnerGraph();
            this.myView.Graph = g;
            this.InitEventObject(ZYVBEventType.Paint);
            if (this.myDocumentElement != null)
            {
                this.myDocumentElement.RefreshView();
            }
            if ((this.myInfo.ShowPageLine && (this.myOwnerControl != null)) && !this.myOwnerControl.PageViewMode)
            {
                using (Pen pen = new Pen(Color.Gray, 1f))
                {
                    pen.DashStyle = DashStyle.Dot;
                    foreach (PrintPage page in this.myPages.Items)
                    {
                        if ((page.Bottom >= ClipRect.Top) && (page.Bottom <= ClipRect.Bottom))
                        {
                            g.DrawLine(pen, ClipRect.Left, page.Bottom, ClipRect.Right, page.Bottom);
                        }
                    }
                }
            }
            this.myView.Graph = innerGraph;
            return true;
        }

        private bool _ignoreLine = false;
        /// <summary>
        /// 是否忽略空行 true 忽略 false 不忽略
        /// </summary>
        public bool IgnoreLine
        {
            set
            {
                _ignoreLine = value;
            }

            get
            {
                return _ignoreLine;
            }
        }

        /// <summary>
        /// 内容是否有变化
        /// </summary>
        /// <returns></returns>
        public bool ViewTimer()
        {
            if (this.bolLastContentChangedFlag)
            {
                this.bolLastContentChangedFlag = false;
                A_Action actionByName = this.GetActionByName("contentchanged");
                if ((actionByName != null) && actionByName.isEnable())
                {
                    //actionByName.Execute();
                    return true;
                }
            }
            return false;
        }

        public ArrayList Actions
        {
            get
            {
                return this.myActions;
            }
        }

        public object All
        {
            get
            {
                if (this.myAllElement == null)
                {
                    this.myAllElement = this.CreateAllObject();
                }
                return this.myAllElement;
            }
        }

        public bool AutoClearSelection
        {
            get
            {
                return this.myContent.AutoClearSelection;
            }
            set
            {
                this.myContent.AutoClearSelection = value;
            }
        }

        public bool CanContentChangeLog
        {
            get
            {
                return ((this.myContentChangeLog != null) && this.myContentChangeLog.CanLog);
            }
        }

        public ZYContent Content
        {
            get
            {
                return this.myContent;
            }
            set
            {
                this.myContent = value;
            }
        }

        public A_ContentChangeLog ContentChangeLog
        {
            get
            {
                return this.myContentChangeLog;
            }
        }

        public ZYTextElement CurrentHoverElement
        {
            get
            {
                return this.myCurrentHoverElement;
            }
            set
            {
                if (this.myCurrentHoverElement != value)
                {
                    ZYTextElement myCurrentHoverElement = this.myCurrentHoverElement;
                    this.myCurrentHoverElement = value;
                    if (myCurrentHoverElement != null)
                    {
                        this.RefreshElement(myCurrentHoverElement);
                    }
                    if (this.myCurrentHoverElement != null)
                    {
                        this.RefreshElement(this.myCurrentHoverElement);
                    }
                }
            }
        }

        public ZYDataSource DataSource
        {
            get
            {
                return this.myDataSource;
            }
            set
            {
                this.myDataSource = value;
            }
        }

        public ZYTextContainer DocumentElement
        {
            get
            {
                return this.myDocumentElement;
            }
            set
            {
                this.myDocumentElement = value;
                this.myElements.Clear();
            }
        }

        public ArrayList Elements
        {
            get
            {
                return this.myElements;
            }
        }

        public ZYVBEventObject EventObj
        {
            get
            {
                if (this.myInfo.EnableScript && (this.myZYVBEngine != null))
                {
                    return this.myZYVBEngine.EventObj;
                }
                return null;
            }
        }

        public bool FormatAll
        {
            get
            {
                return this.bolFormatAll;
            }
            set
            {
                this.bolFormatAll = value;
            }
        }

        public string HideElementNames
        {
            get
            {
                if (this.strHideElementNames == null)
                {
                    return null;
                }
                StringBuilder builder = new StringBuilder();
                foreach (string str in this.strHideElementNames)
                {
                    if (builder.Length == 0)
                    {
                        builder.Append(str);
                    }
                    else
                    {
                        builder.Append(str + ",");
                    }
                }
                return builder.ToString();
            }
            set
            {
                this.strHideElementNames = value.Split(",".ToCharArray());
            }
        }

        public ZYDocumentInfo Info
        {
            get
            {
                return this.myInfo;
            }
            set
            {
                this.myInfo = value;
            }
        }

        public ZYKBBuffer KBBuffer
        {
            get
            {
                return this.myKBBuffer;
            }
            set
            {
                this.myKBBuffer = value;
            }
        }

        public ArrayList Lines
        {
            get
            {
                return this.myLines;
            }
        }

        public float LineSpacing
        {
            get
            {
                return this.fLineSpacing;
            }
            set
            {
                this.fLineSpacing = value;
            }
        }

        public bool Loading
        {
            get
            {
                return this.bolLoading;
            }
            set
            {
                this.bolLoading = value;
            }
        }

        public bool Locked
        {
            get
            {
                return this.bolLocked;
            }
            set
            {
                if (value)
                {
                    this.bolLocked = true;
                    this.Info.ShowExpendHandle = false;
                    this.Info.ShowParagraphFlag = false;
                    this.Info.FieldUnderLine = true;
                    this.myInfo.Printing = true;
                    this.RefreshSize();
                    this.ContentChanged();
                }
                else
                {
                    this.bolLocked = false;
                    this.Info.ShowExpendHandle = !this.Info.ShowExpendHandle;
                    this.Info.ShowParagraphFlag = !this.Info.ShowParagraphFlag;
                    this.Info.FieldUnderLine = !this.Info.FieldUnderLine;
                    this.myInfo.Printing = false;
                    this.RefreshSize();
                    this.ContentChanged();
                }
            }
        }

        public UnderWriteMarkCollection Marks
        {
            get
            {
                return this.myMarks;
            }
        }

        public bool Modified
        {
            get
            {
                return this.myContent.Modified;
            }
            set
            {
                this.myContent.Modified = value;
            }
        }

        public UcEditorControl OwnerControl
        {
            get
            {
                return this.myOwnerControl;
            }
            set
            {
                if (this.myOwnerControl != value)
                {
                    this.myOwnerControl = value;
                    if (this.myOwnerControl != null)
                    {
                        this.myOwnerControl.Document = this;
                        this.myView.Graph = this.myOwnerControl.CreateGraphics();
                        this.myOwnerControl.Pages = this.myPages;
                    }
                }
            }
        }

        public PrintPageCollection Pages
        {
            get
            {
                return this.myPages;
            }
        }

        public System.Drawing.Printing.PageSettings PageSettings
        {
            get
            {
                return this.myPageSettings;
            }
            set
            {
                this.myPageSettings = value;
            }
        }

        public ArrayList RedoList
        {
            get
            {
                return this.myRedoList;
            }
        }

        public ZYTextSaveLogCollection SaveLogs
        {
            get
            {
                return this.mySaveLogs;
            }
        }

        public ZYVBScriptElement Script
        {
            get
            {
                return this.myScript;
            }
        }

        public ArrayList UndoList
        {
            get
            {
                return this.myUndoList;
            }
        }

        public int UndoState
        {
            get
            {
                return this.intUndoState;
            }
        }

        public NameValueList Variables
        {
            get
            {
                return this.myVariables;
            }
        }

        public DocumentView View
        {
            get
            {
                return this.myView;
            }
            set
            {
                this.myView = value;
            }
        }

        /***
         * 页眉信息
         */
        public Dictionary<string, string> PageHeader
        {
            set
            {
                this._pageHeader = value;
            }
            get
            {
                if (_pageHeader == null)
                {
                    if (this.Us.InpatientInfo != null)
                    {
                        _pageHeader = new Dictionary<string, string>();
                        this._pageHeader.Add("姓名", this.Us.InpatientInfo.Patient_Name);
                        this._pageHeader.Add("科别", string.IsNullOrEmpty(this.section_name) ? this.Us.GetSectionName : this.section_name);
                        this._pageHeader.Add("床号", string.IsNullOrEmpty(this.bed_name) ? this.Us.GetBedNo : this.bed_name);
                        this._pageHeader.Add("病区", string.IsNullOrEmpty(this.area_name) ? this.Us.GetBq : this.area_name);
                        this._pageHeader.Add("住院号", this.Us.InpatientInfo.PId);
                        this._pageHeader.Add("性别", this.Us.GetSex);
                        this._pageHeader.Add("入院时间", this.Us.InpatientInfo.In_Time.ToString("yyyy-MM-dd,HH:mm"));
                        this._pageHeader.Add("年龄", Us.InpatientInfo.Age.ToString() + Us.InpatientInfo.Age_unit);
                    }
                }
                return this._pageHeader;
            }
        }

        public bool RefreshPageHeader(InPatientInfo _userInfo)
        {
            this._pageHeader.Clear();
            this._pageHeader = null;
            this.Us.InpatientInfo = _userInfo;
            return true;
        }

        private string section_name = "";
        /// <summary>
        /// 病人科室
        /// </summary>
        public string Section_name
        {
            get { return section_name; }
            set
            {
                this.section_name = value;
            }
        }

        private string area_name = string.Empty;
        public string Area_name
        {
            get
            {
                return area_name;
            }

            set
            {
                this.area_name = value;
            }
        }


        //**************获取内容
        public string GetContent(string strID)
        {
            ET_Document myRecord = new ET_Document();
            ZYTextElement currentElement = this.myContent.CurrentElement;
            string str = "";
            if (((currentElement != null) && myRecord.SetKeyWord(strID)) && this.myDataSource.DBConn.ReadOneRecord(myRecord))
            {
                DataTable dt = new DataTable();
                dt.Select();
                try
                {
                    XmlElement documentElement = myRecord.GetDataXML().DocumentElement;
                    str = documentElement.InnerText;
                }
                catch
                {
                }
            }
            return str;
        }

        /***
         * 获取IP地址
         */
        public string GetUserIP()
        {
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ipAddr = ipHost.AddressList;
            if (ipAddr.Length > 1)
            {
                return ipAddr[1].ToString();
            }
            return ipAddr[0].ToString();
        }

        public void _InsertMedicineForm()
        {
            selectForm = new SelectForm();
            selectForm.Visible = true;
            selectForm.Focus();
            A_InsertMedicine a = new A_InsertMedicine();
            A_Action action = a.Clone();
            if (selectForm.Item != null)
            {
                this._InsertKB(selectForm.KbList, selectForm.Item);
            }
        }
        public void _InsertTest()
        {
            this._InsertKB(selectForm.KbList, selectForm.Item);
        }


        //**********************************页眉页脚************************************
        private void DrawExtString(string txt, Graphics g, Rectangle ClipRectangle)
        {
            //Font DefaultFont = Control.DefaultFont;
            //if ((txt.IndexOf("<") == -1) || (txt.IndexOf(">") == -1))
            //{
            //    using (StringFormat format = new StringFormat())
            //    {
            //        format.Alignment = StringAlignment.Near;
            //        format.LineAlignment = StringAlignment.Near;
            //        g.DrawString(txt, DefaultFont, Brushes.Black, new RectangleF((float)ClipRectangle.Left, (float)ClipRectangle.Top, (float)ClipRectangle.Width, (float)ClipRectangle.Height), format);
            //    }
            //}
            //else
            //{
            //    XmlDocument doc = new XmlDocument();
            //    doc.LoadXml(txt);
            //    int TopCount = ClipRectangle.Top;
            //    using (StringFormat format = new StringFormat())
            //    {
            //        format.Alignment = StringAlignment.Near;
            //        format.LineAlignment = StringAlignment.Center;
            //        format.FormatFlags = StringFormatFlags.NoWrap;
            //        foreach (XmlNode node in doc.DocumentElement.ChildNodes)
            //        {
            //            if (!(node is XmlElement))
            //            {
            //                continue;
            //            }
            //            XmlElement element = (XmlElement)node;
            //            if (element.Name == "line")
            //            {
            //                using (Pen pen = new Pen(Color.Black))
            //                {
            //                    if (element.HasAttribute("thick"))
            //                    {
            //                        pen.Width = Convert.ToInt32(element.GetAttribute("thick"));
            //                    }
            //                    g.DrawLine(pen, ClipRectangle.Left, TopCount, ClipRectangle.Right, TopCount);
            //                    TopCount = (TopCount + ((int)pen.Width)) + 20;
            //                }
            //                continue;
            //            }
            //            if (element.Name == "text")
            //            {
            //                string FontName = DefaultFont.Name;
            //                if (element.HasAttribute("fontname"))
            //                {
            //                    FontName = element.GetAttribute("fontname");
            //                }
            //                int FontSize = (int)DefaultFont.Size;
            //                if (element.HasAttribute("fontsize"))
            //                {
            //                    FontSize = Convert.ToInt32(element.GetAttribute("fontsize"));
            //                }
            //                FontStyle style = FontStyle.Regular;
            //                if (element.HasAttribute("bold"))
            //                {
            //                    style |= FontStyle.Bold;
            //                }
            //                if (element.HasAttribute("italic"))
            //                {
            //                    style |= FontStyle.Italic;
            //                }
            //                if (element.HasAttribute("underline"))
            //                {
            //                    style |= FontStyle.Underline;
            //                }
            //                format.Alignment = StringAlignment.Near;
            //                if (element.HasAttribute("left"))
            //                {
            //                    format.Alignment = StringAlignment.Near;
            //                }
            //                if (element.HasAttribute("center"))
            //                {
            //                    format.Alignment = StringAlignment.Center;
            //                }
            //                if (element.HasAttribute("right"))
            //                {
            //                    format.Alignment = StringAlignment.Far;
            //                }
            //                using (Font font = new Font(FontName, (float)FontSize, style))
            //                {
            //                    float h = g.MeasureString("#", font, 0x2710, format).Height + 10f;
            //                    RectangleF rect = new RectangleF((float)ClipRectangle.Left, (float)TopCount, (float)ClipRectangle.Width, h);
            //                    if (rect.Bottom > ClipRectangle.Bottom)
            //                    {
            //                        return;
            //                    }
            //                    string txt2 = element.InnerText;
            //                    if ((txt2 != null) && (txt2.Length > 0))
            //                    {
            //                        g.DrawString(txt2, font, Brushes.Black, rect, format);
            //                    }
            //                    TopCount += (int)Math.Ceiling((double)h);
            //                    continue;
            //                }
            //            }
            //        }
            //    }
            //}
        }

        public void DrawFooter(Graphics g, Rectangle ClipRectangle)
        {
            this.DrawExtString(this.RuntimeFooterString, g, ClipRectangle);
        }

        public void DrawHead(Graphics g, Rectangle ClipRectangle)
        {
            this.DrawExtString(this.RuntimeHeadString, g, ClipRectangle);
        }


        private string ExecuteVariable(string txt)
        {
            VariableString str = new VariableString(txt);
            str.SetVariable("pageindex", Convert.ToString((int)(this.intPageIndex + this.intPageIndexFix)));
            str.SetVariable("pagecount", this.myPages.Count.ToString());
            DateTime dtm = ZYTime.GetServerTime();
            str.SetVariable("year", dtm.Year.ToString());
            str.SetVariable("month", dtm.Month.ToString());
            str.SetVariable("dy", dtm.Day.ToString());
            str.SetVariable("hour", dtm.Hour.ToString());
            str.SetVariable("minute", dtm.Minute.ToString());
            str.SetVariable("secend", dtm.Second.ToString());
            return str.Execute();
        }

        protected string strFooterString = "<a><text fontname='仿宋_GB2312' fontsize='12' bold='bold' center='center'>XXX医院</text><text fontname='仿宋_GB2312' fontsize='18' bold='bold' center='center'>入 院 记 录</text><text fontname='仿宋_GB2312' fontsize='12' center='center'>姓名：张三    住院号：009988    床号：10床    科室：神经内一科</text><line thick='1'></line></a>";
        protected string strHeadString = "<a><line thick='1'></line><text fontname='宋体_GB2312' fontsize='10' center='center' >第[%pageindex%]页 / 共[%pagecount%]页</text></a>";
        public string RuntimeFooterString
        {
            get
            {
                return this.ExecuteVariable(this.strFooterString);
            }
        }

        public string RuntimeHeadString
        {
            get
            {
                return this.ExecuteVariable(this.strHeadString);
            }
        }

        private int intPageIndex = 0;
        private int intPageIndexFix = 1;
        public int PageIndex
        {
            get
            {
                return this.intPageIndex;
            }
            set
            {
                this.intPageIndex = value;
            }
        }

        public int PageIndexFix
        {
            get
            {
                return this.intPageIndexFix;
            }
            set
            {
                this.intPageIndexFix = value;
            }
        }

        public void DrawDocument(Graphics g, Rectangle ClipRectangle)
        {
            this.myView.ViewRect = ClipRectangle;
            Graphics gBack = this.myView.GetInnerGraph();
            this.myView.Graph = g;
            this.InitEventObject(ZYVBEventType.Paint);
            if (this.myDocumentElement != null)
            {
                this.myDocumentElement.RefreshView();
            }
            this.myView.Graph = gBack;
        }

        public int FooterHeight
        {
            get
            {
                return this.intFooterHeight;
            }
            set
            {
                this.intFooterHeight = value;
            }
        }

        public string FooterString
        {
            get
            {
                return this.strFooterString;
            }
            set
            {
                this.strFooterString = value;
            }
        }

        public int HeadHeight
        {
            get
            {
                return this.intHeadHeight;
            }
            set
            {
                this.intHeadHeight = value;
            }
        }

        public string HeadString
        {
            get
            {
                return this.strHeadString;
            }
            set
            {
                this.strHeadString = value;
            }
        }

        /// <summary>
        /// c插入公式的时候转换尺寸用到
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public int PixelToDocumentUnit(int len)
        {
            return GraphicsUnitConvert.Convert(len, GraphicsUnit.Pixel, this.intDocumentGraphicsUnit);
        }

        private GraphicsUnit intDocumentGraphicsUnit = GraphicsUnit.Document;
        public GraphicsUnit DocumentGraphicsUnit
        {
            get
            {
                return this.intDocumentGraphicsUnit;
            }
            set
            {
                this.intDocumentGraphicsUnit = value;
            }
        }

        private ArrayList printImages;

        public ArrayList PrintImages
        {
            get { return printImages; }
            set { printImages = value; }
        }

        /// <summary>
        /// 默认Xml格式
        /// </summary>
        /// <returns></returns>
        private string GetXmlContent()
        {
            XmlDocument tempxmldoc = new XmlDocument();
            tempxmldoc.LoadXml("<emrtextdoc/>");
            this.ToXML(tempxmldoc.DocumentElement);
            return tempxmldoc.OuterXml;
        }


        /// <summary>
        /// 保存模版
        /// </summary>
        /// <param name="tid">模版ID</param>
        public void saveTemplate(int tid)
        {
            XmlDocument tempxmldoc = new XmlDocument();
            tempxmldoc.PreserveWhitespace = true;
            tempxmldoc.LoadXml("<emrtextdoc/>");
            this.ToXML(tempxmldoc.DocumentElement);
            string temp = tempxmldoc.OuterXml;

            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.LoadXml(temp);

            App.InsertLabelContent(tid, doc);//模版ID 和文书内容
            //App.InsertModel();
        }

        //记录撤销签名
        public bool SaveTrue = false;

        public void RemoveInput(ZYTextInput input)
        {
            input.Parent.RemoveChild(input);
            this.ContentChanged();
        }


        ///// <summary>
        ///// 插入会诊 一暂存
        ///// </summary>
        ///// <param name="style"></param>
        //public void saveDocument(int style)
        //{
        //    //新增
        //    if (this.Us.Tid == 0)
        //    {
        //        Bifrost.WebReference.OracleParameter[] xmlParDoc = new Bifrost.WebReference.OracleParameter[1];
        //        xmlParDoc[0] = new Bifrost.WebReference.OracleParameter();
        //        xmlParDoc[0].ParameterName = "Patients_Doc";
        //        xmlParDoc[0].Value = xmlDoc;
        //        xmlParDoc[0].OracleType = OracleType.Clob;
        //        int tid = App.GenId("T_Patients_Doc", "TID");
        //        string strinsert =
        //            string.Format("insert into T_Patients_Doc(tid,CREATEID, pid, textkind_id, patients_doc, belongtosys_id, sickkind_id, textname,submitted,PATIENT_ID,DOC_NAME) " +
        //                          "values('{0}','{1}','{2}','{3}',:Patients_Doc,'{4}','{5}','{6}','{7}','{8}','{9}')"
        //                          , tid.ToString()                                                  //文书ID
        //                          , (_isTemporary == true ? App.UserAccount.UserInfo.User_id : "") //是否提交按钮
        //                          , PID
        //                          , textKind_ID
        //                          , belongToSys_ID
        //                          , sickKind_ID
        //                          , textName
        //                          , (_isTemporary == true ? "Y" : "N")  //暂存/提交
        //                          , Us.InpatientInfo.Id
        //                          ,App.GetSystemTime().ToString("yyyy-MM-dd HH:mm");
        //        //如果保存文书成功
        //        if (App.ExecuteSQL(strinsert, xmlParDoc) > 0)
        //        {
        //            this.Us.Tid = tid;
        //            if (Us.IsMore)
        //            {
        //                if (this.Us.RecordTime == "")
        //                {
        //                    this.Us.RecordTime = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm");
        //                }
        //                string sql2 = string.Format(" insert into t_quality_text"
        //                                          + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
        //                                          + " values"
        //                                          + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')",
        //                                          Us.RecordTime + "   " + Us.RecordText
        //                                          , textKind_ID
        //                                          , Us.InpatientInfo.PId
        //                                          , Convert.ToDateTime(Us.RecordTime).ToString("yyyy-MM-dd HH:mm")
        //                                          , tid
        //                                          , Us.InpatientInfo.Id);
        //                if (App.ExecuteSQL(sql2) < 1)
        //                {
        //                    App.Msg("质控表保存失败");
        //                }
        //            }
        //            else
        //            {
        //                string sql2 = string.Format(" insert into t_quality_text"
        //                                           + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
        //                                           + " values"
        //                                           + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')",
        //                                           this.Us.TextName
        //                                           , textKind_ID
        //                                           , Us.InpatientInfo.PId
        //                                           , App.GetSystemTime().ToString("yyyy-MM-dd HH:mm")
        //                                           , tid
        //                                           , Us.InpatientInfo.Id);
        //                if (App.ExecuteSQL(sql2) < 1)
        //                {
        //                    App.Msg("质控表保存失败");
        //                }
        //            }
        //        }
        //    }
        //    else //修改 
        //    {
        //        String sql = string.Format("update T_PATIENTS_DOC set PATIENTS_DOC = :doc1,DOC_NAME = '{2}' where TID = '{0}' AND PATIENT_ID = '{1}' ", Us.Tid, this.Us.InpatientInfo.Id, (Us.RecordTime.Trim() == "" ? "" : Us.RecordTime + "   " + Us.RecordText));
        //        OracleParameter[] xmlPars = new OracleParameter[1];
        //        xmlPars[0] = new OracleParameter();
        //        xmlPars[0].ParameterName = "doc1";
        //        xmlPars[0].Value = tempxmldoc.OuterXml;
        //        xmlPars[0].OracleType = OracleType.Clob;
        //        if (App.ExecuteSQL(sql, xmlPars) > 0)
        //        {
        //            App.Msg("修改成功！");
        //        }
        //    }
        //}

        //pascal内容
        //#region
        //if (this.Us.TextKind_id == 158 && blfalse)
        //{
        //    XmlNodeList list = tempxmldoc.GetElementsByTagName("input");
        //    Dictionary<string, string> decList = new Dictionary<string, string>();
        //    decList.Add("X线号", "");
        //    decList.Add("CT号", "");
        //    decList.Add("MRI号", "");
        //    decList.Add("病理检验号", "");
        //    foreach (XmlNode xn in list)
        //    {
        //        //CT号 MRI号 病理检验号
        //        if (xn.Attributes["name"].Value != null)
        //        {
        //            if ((xn.Attributes["name"].Value == "X线号"
        //                || xn.Attributes["name"].Value == "CT号"
        //                || xn.Attributes["name"].Value == "MRI号"
        //                || xn.Attributes["name"].Value == "病理检验号")
        //                && xn.Attributes["deleter"] == null)
        //            {
        //                string outText = "";
        //                if (xn.ChildNodes.Count > 0)
        //                {
        //                    foreach (XmlNode childNode in xn.ChildNodes)
        //                    {
        //                        if (childNode.Attributes["deleter"] == null)
        //                        {
        //                            outText += childNode.InnerText;
        //                        }
        //                    }
        //                }
        //                decList[xn.Attributes["name"].Value] = outText;
        //            }
        //        }
        //    }
        //    if (App.GetDataSet("SELECT PATIENT_ID FROM T_PASC WHERE PATIENT_ID = '" + this.Us.InpatientInfo.Id + "'").Tables[0].Rows.Count < 1)
        //    {
        //        App.ExecuteSQL(string.Format("INSERT INTO T_PASC(PID,P1,P2,P3,P4,PATIENT_ID)VALUES('{0}','{1}','{2}','{3}','{4}','{5}')"
        //            , this.Us.InpatientInfo.PId
        //            , decList["X线号"]
        //            , decList["CT号"]
        //            , decList["MRI号"]
        //            , decList["病理检验号"]
        //            , this.Us.InpatientInfo.Id.ToString()));
        //    }
        //    else
        //    {
        //        App.ExecuteSQL(string.Format("UPDATE T_PASC SET P1='{0}',P2='{1}',P3='{2}',p4 ='{3}' WHERE PATIENT_ID = '{4}'"
        //           , decList["X线号"]
        //           , decList["CT号"]
        //           , decList["MRI号"]
        //           , decList["病理检验号"]
        //           , this.Us.InpatientInfo.Id.ToString()));
        //    }
        //}
        //#endregion
        public void ClearCreate()
        {
            ArrayList list = new ArrayList();
            this.ClearDeleteCreate(this.DocumentElement, list);
            if (list.Count > 0)
            {
                foreach (ZYTextElement element in list)
                {

                    element.Parent.ChildElements.Remove(element);
                }
            }
        }
        void ClearDeleteCreate(ZYTextContainer container, ArrayList list)
        {
            foreach (ZYTextElement element in container.ChildElements)
            {
                if (element.Deleteted)
                {
                    list.Add(element);
                }
                else
                {
                    element.CreatorIndex = -1;
                    element.Attributes.RemoveAttribute("operatercreater");
                    if (element is ZYTextContainer)
                    {
                        ClearDeleteCreate((ZYTextContainer)element, list);
                    }
                }
            }
        }
        /// <summary>
        /// 验证输入元素
        /// </summary>
        /// <returns></returns>
        public bool CheckContent()
        {
            foreach (object childElement in this.Elements)
            {
                if (childElement is ZYTextInput)
                {
                    ZYTextInput _input = childElement as ZYTextInput;
                    if (_input.BolPass)
                    {
                        App.Msg("文本域输入字符少于设置长度");
                        this.myContent.SetSelection(_input.Index + 1, 0);
                        return false;
                    }
                }
            }
            return true;
        }

        private int ExecuteDeleter(string tableName, string primaryid, string id)
        {
            string sql = string.Format("DELETE {0} WHERE {1} = '{2}'", tableName, primaryid, id);
            return App.ExecuteSQL(sql);
        }

        //private bool isSubmit = false; //提交/暂存
        /***
         * 文书保存文书
         */
        public void saveDocument(object sender, EventArgs e)
        {
            try
            {
                //SaveImgTo();
                if (Us.TextKind_id == 0 || this.Locked)
                {
                    App.Msg("文书已经锁定！");
                    return;
                }

                //提交按钮操作 true 暂存false
                bool blfalse = false;
                if (sender is ButtonItem)
                {
                    blfalse = (sender as ButtonItem).Name == "tsbtnCommit";
                }
                else if (sender is ButtonX)
                {
                    blfalse = (sender as ButtonX).Name == "btnSave";
                }

                #region 性别关键字检查

                if (blfalse)
                {
                    StringBuilder filterMessage;
                    string first;
                    FindWords(out filterMessage, out first);
                    if (filterMessage.Length > 0)
                    {
                        filterMessage.Insert(0, "该病人性别为【" + (this.Us.InpatientInfo.Gender_Code == "0" ? "男" : "女") + "】文书中含有下列关键字,继续保存点是,不保存点否\n");
                        if (MessageBox.Show(filterMessage.ToString(), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                        {
                            _Find(first, 0);
                            return;
                        }
                    }
                }

                #endregion


                /***
                * 验证元素
                */
                if (blfalse && !CheckContent())
                {
                    return;
                }

                if (blfalse && this.Us.TextKind_id != 1724)
                {
                    if (!SaveTrue)
                    {
                        if (this.isHaveTextId())
                        {
                            if (!_InsertSignature())
                            {
                                return;
                            }
                        }
                        else
                        {
                            if (!_otherTextSign())
                            {
                                return;
                            }
                            this.ContentChanged();
                        }
                    }
                }
                //获取文书XMl
                XmlDocument tempxmldoc = new XmlDocument();
                tempxmldoc.PreserveWhitespace = true;
                tempxmldoc.LoadXml("<emrtextdoc/>");
                this.ToXML(tempxmldoc.DocumentElement);
                bool isTakeSuperiorZz = false;
                bool isTakeSuperiorZr = false;
                if (this.Us.TextKind_id == 126)
                {
                    if (this.Us.Tid == 0)
                    {
                        using (frmMessageBox messageBox = new frmMessageBox())
                        {
                            messageBox.ShowDialog();
                            if (messageBox.Succeed)
                            {
                                isTakeSuperiorZz = messageBox.IsZZCheck;
                                isTakeSuperiorZr = messageBox.IsZRCheck;
                            }
                        }
                    }
                    else
                    {

                        string sql = "SELECT ISRAPLACEHIGHTDOCTOR,ISRAPLACEHIGHTDOCTOR2 FROM T_Patients_Doc T WHERE T.TID = '" + this.Us.Tid + "'";
                        DataTable dt = App.GetDataSet(sql).Tables[0];
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            isTakeSuperiorZz = dt.Rows[0]["ISRAPLACEHIGHTDOCTOR"].ToString() == "Y";
                            isTakeSuperiorZr = dt.Rows[0]["ISRAPLACEHIGHTDOCTOR2"].ToString() == "Y";
                        }
                    }
                }
                //if (blfalse)
                //{
                //    bool isOkdiagnose = false;
                //    string okDiagnoseTime = "";
                //    string message =
                //        App.checkDocRule(this.Us.InpatientInfo.Id.ToString(),
                //        this.Us.TextKind_id.ToString(), tempxmldoc,
                //        out isOkdiagnose, out okDiagnoseTime, isTakeSuperiorZz ? 2 : isTakeSuperiorZr ? 1 : -1
                //        , Us.Tid != 0 ? true : false);
                //    ExecuteDeleter("T_DIAGNOSE_UNROLE", "TID", this.Us.Tid.ToString());
                //    if (message != "")
                //    {
                //        App.Msg(message);
                //        if (isOkdiagnose)
                //        {
                //            string sql = string.Format("INSERT INTO T_DIAGNOSE_UNROLE(TID,M_DIAGNOSE_TIME) VALUES('{0}',to_TIMESTAMP('{1}','yyyy-MM-dd hh24:mi:ss'))"
                //                , this.Us.Tid, okDiagnoseTime);
                //            App.ExecuteSQL(sql);
                //        }
                //        else
                //        {
                //            return;
                //        }
                //    }
                //}

                //OracleParameter[] xmlPars = new OracleParameter[1];
                //xmlPars[0] = new OracleParameter();
                //xmlPars[0].ParameterName = "patients_doc";
                //xmlPars[0].Value = tempxmldoc.OuterXml;
                //xmlPars[0].OracleType = OracleType.Clob;
                //修改
                string haveSuperior = (HaveSuperiorSign(blfalse) ? "Y" : "N");
                //string havaTube = (HaveTubeBedSign(blfalse) ? "Y" : "N");
                string textTitle = "";
                string qualityTitle = "";
                DateTime sysTime = App.GetSystemTime();
                XmlNodeList nodeList = tempxmldoc.GetElementsByTagName("div");
                foreach (XmlNode childNode in nodeList)
                {
                    if (childNode.Attributes["timeTitle"] != null && childNode.Attributes["timeTitle"].Value == "Y")
                    {
                        textTitle = childNode.Attributes["title"] != null ? childNode.Attributes["title"].Value : "";
                        break;
                    }
                }
                if (textTitle != "")
                {
                    qualityTitle = textTitle;
                }

                if (qualityTitle == "")
                {
                    XmlNodeList inputNodeList = tempxmldoc.GetElementsByTagName("input");
                    foreach (XmlNode childNode in inputNodeList)
                    {
                        if (childNode.Attributes["name"] != null)
                        {
                            string writeTime = childNode.Attributes["name"].Value;
                            if (writeTime == "记录日期" || writeTime == "us_jlrq" || writeTime == "死亡时间" || writeTime == "出院时间" || writeTime == "出院日期" || writeTime == "书写时间")
                            {
                                qualityTitle = childNode.InnerText.Replace("，", " ") + "  " + this.Us.TextName;
                                textTitle = qualityTitle;
                                break;
                            }
                        }
                    }
                }
                if (textTitle == "" && this.Us.RecordTime != "")
                {
                    textTitle = this.Us.RecordTime + "   " + this.Us.RecordText;
                    qualityTitle = this.Us.RecordTime + "  " + this.Us.RecordText;
                }
                if (textTitle == "")
                {
                    textTitle = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm") + "   " + this.Us.TextName;
                    qualityTitle = textTitle;
                }
                try
                {
                    qualityTitle += isTakeSuperiorZz == true ? "代主治医师查房记录" : "";
                    qualityTitle += isTakeSuperiorZr == true ? "代主任医师查房记录" : "";
                    if (Us.Tid != 0)
                    {
                        //修改文书内容
                        if (blfalse) //点的提交按钮
                        {
                            DataTable dt = App.GetDataSet(string.Format("select submitted from T_PATIENTS_DOC where TID = {0} AND PATIENT_ID = '{1}'", Us.Tid, this.Us.InpatientInfo.Id)).Tables[0];
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                string submmit = dt.Rows[0][0].ToString();
                                if (submmit == "Y")
                                {
                                    LogHelper.SystemLog("修改", this.Us.Tid.ToString(), this.Us.InpatientInfo.PId.ToString(), this.Us.InpatientInfo.Id);
                                }
                                else
                                {
                                    LogHelper.SystemLog("创建", this.Us.Tid.ToString(), this.Us.InpatientInfo.PId.ToString(), this.Us.InpatientInfo.Id);
                                    if (this.Us.TextKind_id == 890)
                                    {
                                        InsertJobTemp(qualityTitle);
                                    }
                                }
                            }
                        }
                        String sql = string.Format("update T_PATIENTS_DOC set HAVEDOCTORSIGN = '{3}' ,ISHIGHERSIGN = '{4}',HAVEHIGHERSIGN = '{5}',submitted='{6}',highersignuserid = '{7}' {2} where TID = {0} AND PATIENT_ID = '{1}' ",
                            Us.Tid,
                            this.Us.InpatientInfo.Id,
                            textTitle == "" ? "" : ",doc_name ='" + textTitle + "'",
                            "N",
                            TextSuperiorSignature,
                            haveSuperior,
                            (blfalse == true ? "Y" : "N"),
                            this.SuporSign);
                        if (App.ExecuteSQL(sql) > 0)
                        {
                            App.UpLoadFtpPatientDoc(tempxmldoc.OuterXml, Us.Tid.ToString() + ".xml", Us.InpatientInfo.Id.ToString());
                            //InsertKeys(tempxmldoc, this.Us.Tid);
                            #region 质控表
                            if (blfalse)
                            {
                                if (App.GetDataSet("SELECT pid from t_quality_text where tid = '" + Us.Tid + "'").Tables[0].Rows.Count < 1)
                                {
                                    //如果质控表没数据 插入该数据
                                    string sql2 = string.Format(" insert into t_quality_text"
                                                              + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
                                                              + " values"
                                                              + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')"
                                                              , ""
                                                              , Us.TextKind_id
                                                              , Us.InpatientInfo.PId
                                                              , sysTime.ToString("yyyy-MM-dd HH:mm")
                                                              , Us.Tid, Us.InpatientInfo.Id);
                                    App.ExecuteSQL(sql2);
                                }
                                string sql3 = string.Format("UPDATE t_quality_text SET textname ='{0}' where tid = {1}"
                                    , qualityTitle
                                    , Us.Tid);
                                int i = App.ExecuteSQL(sql3);
                            }
                            #endregion
                            App.Msg("文书保存成功！");
                        }
                        else
                        {
                            App.Msg("文书保存失败！");
                            return;
                        }
                    }
                    else
                    {
                        //文书Tid
                        if (!this.Us.IsMore)
                        {
                            DataTable havaCount =
                                App.GetDataSet(string.Format("SELECT COUNT(t.pid) FROM T_PATIENTS_DOC T WHERE T.PATIENT_ID = '{0}' AND t.textkind_id = '{1}'", this.Us.InpatientInfo.Id, this.Us.TextKind_id)).Tables[0];
                            if (havaCount != null && Convert.ToInt32(havaCount.Rows[0][0]) > 0)
                            {
                                App.Msg("该文书已经存在！可能别的账号登录已经书写提交。");
                                return;
                            }
                        }

                        int tid = App.GenId("T_Patients_Doc", "TID");
                        string strinsert =
                            string.Format("insert into T_Patients_Doc(tid,CREATEID, pid, textkind_id, belongtosys_id, sickkind_id, textname,submitted,PATIENT_ID,DOC_NAME,HAVEDOCTORSIGN,ISHIGHERSIGN,HAVEHIGHERSIGN,highersignuserid,ISRAPLACEHIGHTDOCTOR,ISRAPLACEHIGHTDOCTOR2,SECTION_NAME,BED_NO) " +
                                          "values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}')"
                                          , tid.ToString()                                                 //文书ID
                                          , App.UserAccount.UserInfo.User_id //是否提交按钮
                                          , Us.InpatientInfo.PId
                                          , Us.TextKind_id
                                          , Us.Belong_ToSys_ID
                                          , Us.SickKind_ID
                                          , Us.OldTextName
                                          , (blfalse == true ? "Y" : "N")  //暂存/提交
                                          , Us.InpatientInfo.Id
                                          , textTitle
                                          , "N"
                                          , TextSuperiorSignature
                                          , haveSuperior
                                          , this.SuporSign
                                          , (isTakeSuperiorZz == true ? "Y" : "N")
                                          , (isTakeSuperiorZr == true ? "Y" : "N")
                                          , this.Us.InpatientInfo.Section_Name
                                          , this.Us.InpatientInfo.Sick_Bed_Name);
                        //如果保存文书成功
                        if (App.ExecuteSQL(strinsert) > 0)
                        {
                            this.Us.Tid = tid;
                            App.UpLoadFtpPatientDoc(tempxmldoc.OuterXml, Us.Tid.ToString() + ".xml", Us.InpatientInfo.Id.ToString());
                            if (blfalse)
                            {
                                LogHelper.SystemLog("创建", this.Us.Tid.ToString(), this.Us.InpatientInfo.PId.ToString(), this.Us.InpatientInfo.Id);
                                if (this.Us.TextKind_id == 890)
                                {
                                    InsertJobTemp(qualityTitle);
                                }
                                /***
                                 * 质控表
                                 * 
                                 */
                                string sql2 = string.Format(" insert into t_quality_text"
                                                          + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
                                                          + " values"
                                                          + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')",
                                                          qualityTitle
                                                          , Us.TextKind_id
                                                          , Us.InpatientInfo.PId
                                                          , sysTime.ToString("yyyy-MM-dd HH:mm")
                                                          , tid
                                                          , Us.InpatientInfo.Id);

                                /***
                                 * 临床路径文书相关
                                 */
                                //OracleParameter op1 = new OracleParameter();
                                //op1.ParameterName = "yizhu";
                                //op1.Value = tid;
                                //OracleParameter op2 = new OracleParameter();
                                //op2.ParameterName = "patient_id";
                                //op2.Value = this.Us.InpatientInfo.Id;
                                //OracleParameter op3 = new OracleParameter();
                                //op3.ParameterName = "tiem";
                                //op3.Value = sysTime.ToString("yyyy-MM-dd HH:mm");
                                //OracleParameter op4 = new OracleParameter();
                                //op4.ParameterName = "execute_person";
                                //op4.Value = App.UserAccount.UserInfo.User_id + "|" + App.UserAccount.UserInfo.User_name;

                                //App.RunProcedure("ecp.proc_excute_patientdoc", new OracleParameter[] { op1, op2, op3, op4 });
                                if (App.ExecuteSQL(sql2) < 1)
                                {
                                    App.Msg("质控表保存失败");
                                }
                            }
                            App.Msg("文书保存成功！");
                        }
                        else
                        {
                            App.Msg("文书保存失败!");
                        }
                    }
                }
                catch (Exception x)
                {
                    App.Msg(x.Message);
                }
                if (blfalse)
                {
                    //InsertMeg();
                }

                /***
                 * 传递文书 TID 过去
                 */
                if (this.OnBackTextId != null)
                {
                    BackEvenHandle backHandle = new BackEvenHandle();
                    backHandle.Style = 1;
                    backHandle.Submit = blfalse;
                    backHandle.Para = this.Us.Tid.ToString();
                    backHandle.XmlString = tempxmldoc.OuterXml;
                    backHandle.User = this.Us;
                    backHandle.SctionName = this.Us.GetSectionName;
                    OnBackTextId(this, backHandle);
                }
                ExcuteDiagnoseSql();
                this.HaveSuperiorSignature = haveSuperior;
                //this.HaveTubebedSign = havaTube;
                this.Modified = false;
                this.RefreshPages();
                SaveTrue = false;
                //UpLoadImg.Instance.SaveImags(this.PageHeader, this.Us, tempxmldoc);
                //InsertText(tempxmldoc,"");
            }
            catch (Exception ex)
            {
                App.Msg(ex.Message + "|\n" + ex.TargetSite);
            }
        }

        public void SaveOk()
        {
            if (this.OnBackTextId != null)
            {
                BackEvenHandle b = new BackEvenHandle();
                b.Style = 4;
                this.OnBackTextId(this, b);
            }
        }

        //void InsertText(XmlDocument xml, string time)
        //{
        //    //int tid = App.GenId("T_Patients_Doc", "TID");
        //    string strinsert =
        //              string.Format("insert into T_Patients_Doc(tid,CREATEID, pid, textkind_id, belongtosys_id, sickkind_id, textname,submitted,PATIENT_ID,DOC_NAME,SECTION_NAME,BED_NO) " +
        //                            "values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')"
        //                            , tid.ToString()    //tid                                             //文书ID
        //                            , App.UserAccount.UserInfo.User_id //是否提交按钮
        //                            , Us.InpatientInfo.PId //pid
        //                            , 111  //文书类型ID
        //                            , Us.Belong_ToSys_ID //
        //                            , Us.SickKind_ID //
        //                            , ""   //textname
        //                            , "Y"  //暂存/提交
        //                            , Us.InpatientInfo.Id
        //                            , ""    //docName
        //                            , this.Us.InpatientInfo.Section_Name
        //                            , this.Us.InpatientInfo.Sick_Bed_Name);
        //    App.UpLoadFtpPatientDoc(tempxmldoc.OuterXml, Us.Tid.ToString() + ".xml", Us.InpatientInfo.Id.ToString());

        //    XmlDocument newDocument = new XmlDocument();
        //    newDocument.PreserveWhitespace = true;
        //    //this.load
        //    //App.UpLoadFtpPatientDoc(newDocument.OuterXml, tid.ToString() + ".xml", Us.InpatientInfo.Id.ToString());
        //}

        const string docforimg_sql = "insert into t_docforimg_list(patient_id, textkind_id)values('{0}', '{1}')";
        public bool InsertMeg()
        {
            if (App.ExecuteSQL(string.Format(docforimg_sql, this.Us.InpatientInfo.Id, this.Us.TextKind_id)) > 0)
                return true;
            else
                return false;
        }

        const string job_temp_sql = "insert into t_job_temp(pid, operate_type, operate_time, patient_id)values('{0}', '{1}', to_TIMESTAMP('{2}','yyyy-MM-dd hh24:mi'), '{3}')";
        public bool InsertJobTemp(string time)
        {
            string timeStr;
            try
            {
                timeStr = App.GetTimeString(time);
                Convert.ToDateTime(timeStr);
            }
            catch
            {
                timeStr = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm");
            }
            string sql = string.Format(job_temp_sql, this.Us.InpatientInfo.PId, "交班记录", timeStr, this.Us.InpatientInfo.Id);
            if (App.ExecuteSQL(sql) > 0)
                return true;
            else
                return false;
        }
        static DataTable filterSexDt = null;
        public void FindWords(out StringBuilder filterMessage, out string first)
        {
            StringBuilder myStr = new StringBuilder();
            if (filterSexDt == null)
                filterSexDt = App.GetDataSet("select phrase,sex from t_sex_phrase").Tables[0];
            this.myDocumentElement.GetFinalText(myStr);
            string text = myStr.ToString();
            filterMessage = new StringBuilder();
            first = string.Empty;
            DataRow[] rows = filterSexDt.Select(string.Format("sex = '{0}'", this.Us.InpatientInfo.Gender_Code == "0" ? 1 : 0));
            if (rows != null && rows.Length > 0)
            {
                foreach (DataRow row in rows)
                {
                    if (text.Contains(row[0].ToString()))
                    {
                        filterMessage.Append("【");
                        filterMessage.Append(row[0].ToString());
                        filterMessage.Append("】\n");
                        if (first == string.Empty)
                            first = row[0].ToString();
                    }
                }
            }
        }

        /// <summary>
        /// 获取图片
        /// </summary>
        /// <returns></returns>
        public Image[] GetPreImages()
        {
            int pagesCount = this.Pages.Count;
            Image[] images = new Image[pagesCount];
            int currentIndex = 0;
            while (currentIndex < pagesCount)
            {
                images[currentIndex] = this.GetPreViewImage(currentIndex, 0, 0);
                currentIndex++;
            }
            return images;
        }

        public void print()
        {
            (new DocPrint(this)).print();
        }

        /// <summary>
        /// 将图片保存到指定路径
        /// </summary>
        /// <param name="fileName"></param>
        public void SaveImgTo(string text_id, string inpatient_id)
        {
            Image[] Images = this.GetPreImages();
            TextIdToPageIndex();
            string directoryPath = App.SysPath + "\\temp"; //如果没有该目录就创建
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            int imageCount = Images.Length;
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < imageCount; i++)
            {
                Image img = Images[i];
                builder.Append(inpatient_id);
                builder.Append("_");
                builder.Append(text_id);
                builder.Append("_");
                builder.Append(i + 1);
                builder.Append("_");
                builder.Append(imageCount);
                string fileSaveName = directoryPath + "\\" + builder.ToString() + ".jpg";
                img.Save(fileSaveName, ImageFormat.Jpeg);
                img.Dispose();
                builder.Remove(0, builder.Length);
            }
        }

        /// <summary>
        /// 找到 所在页码
        /// </summary>
        /// <returns></returns>
        private string[] TextIdToPageIndex()
        {
            List<ZYTextSplit> splitList = GetSplitList();
            string updateSql = "UPDATE T_PATIENTS_DOC T SET T.pageindex = '{0}',t.pagecount = '{1}' WHERE T.TID = '{2}'";
            if (splitList != null)
            {
                ArrayList list = new ArrayList();
                string[] strs = new string[splitList.Count];
                ZYTextSplit firstList = splitList[0];
                strs[0] = string.Format(updateSql, "1", Pages.Count, firstList.textId); // + "|" + "1"
                for (int i = 0; i < splitList.Count - 1; i++)
                {
                    ZYTextSplit split = splitList[i];
                    int countAdd = 1;
                    ZYTextLine line = split.OwnerLine;
                    ZYTextLine line2 = (ZYTextLine)this.myLines[this.myLines.IndexOf(line) + 1];
                    foreach (PrintPage printpage in this.myPages.Items)
                    {
                        if (printpage.Top + printpage.Height > line2.RealTop)
                        {
                            strs[i + 1] = string.Format(updateSql, countAdd.ToString(), Pages.Count, splitList[i + 1].textId); string.Format("UPDATE T_PATIENTS_DOC T SET T.DOC_PAGE = '{0}' WHERE T.TID = '{1}'", countAdd.ToString(), splitList[i + 1].textId); //splitList[i + 1].textId + "=" + countAdd.ToString();
                            break;
                        }
                        countAdd++;
                    }
                }
                return strs;
            }
            else
            {
                return new string[] { string.Format(updateSql, "1", Pages.Count, this.Us.Tid) };
            }
        }

        public Image[] GetDocForImages(out string[] param)
        {
            param = TextIdToPageIndex();
            return this.GetPreImages();
        }

        //private bool InsertKeys(XmlDocument _Document, int _tid)
        //{
        //    //            T_ELE_SIGN 签名表
        //    //TID NUMBER Y 文书主键
        //    //SIGNNUM NUMBER Y 签名序号
        //    //CLIENTSIGNCERT NUMBER Y KEY盘证书
        //    //RCLIENTSIGNVALUE VARCHAR2(4000) Y 签名值
        //    //签名：  OUTXML文书整个XML字符串
        //    string outXml = _Document.OuterXml;
        //    string signvalue = App.CL_SignData(App.strContainerName, outXml);
        //    //获取证书序号：
        //    string signnum = App.CL_GetCertInfo(App.strClientsignCert, 2);
        //    //App.strClientsignCert 证书 

        //    string timeStamps = App.Web_CreateTSByOriginalData(outXml);
        //    OracleParameter[] xmlPars = new OracleParameter[1];
        //    xmlPars[0] = new OracleParameter();
        //    xmlPars[0].ParameterName = "timestamps";
        //    xmlPars[0].Value = timeStamps;
        //    xmlPars[0].OracleType = OracleType.Clob;
        //    string sql =
        //        string.Format("INSERT INTO T_ELE_SIGN(TID,SIGNNUM,CLIENTSIGNCERT,RCLIENTSIGNVALUE,timestamps) " +
        //                      " VALUES('{0}','{1}','{2}','{3}',:timestamps)"
        //                      , _tid, signnum, App.strClientsignCert, signvalue);
        //    if (App.ExecuteSQL(sql, xmlPars) > 0)
        //    {
        //        return true;
        //    }
        //    return false;
        //}

        /***
         * 管床医生是否签名
         */
        public bool HaveTubeBedSign(bool isSubmit)
        {
            if (isSubmit == false)
            {
                return false;
            }
            if (isHaveTextId())
            {
                ArrayList qmList = this.GetQmList("普通医师签名");
                if (qmList == null)
                {
                    return false;
                }
                if (qmList.Count > 0)
                {
                    ZYTextInput signInput = qmList[qmList.Count - 1] as ZYTextInput;
                    if (App.IsNeedCheck(signInput.ID))
                    {
                        foreach (ZYTextInput _input in qmList)
                        {
                            if (_input.ID == this.Us.InpatientInfo.Sick_Doctor_Id)
                                return true;
                        }
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            else
            {
                List<ZYTextInput> signQm = this.GetQmList();
                if (signQm == null)
                {
                    return true;
                }

                ZYTextInput ptQm = null;
                ZYTextInput gcQm = null;
                foreach (ZYTextInput qmInput in signQm)
                {
                    if (qmInput.Name == "普通医师签名")
                    {
                        ptQm = qmInput;
                    }
                    if (qmInput.Name == "管床医师签名")
                    {
                        gcQm = qmInput;
                    }
                }

                if (gcQm != null)
                {
                    if (gcQm.ID != "" && gcQm.Text.Length > 5)
                    {
                        return true;
                    }
                }

                if (ptQm != null)
                {
                    if (string.IsNullOrEmpty(ptQm.ID.Trim()))
                    {
                        return false;
                    }
                    if (ptQm.Text.Length > 5)
                    {
                        if (App.IsNeedCheck(ptQm.ID))
                        {
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 右键插入管床医师签名
        /// </summary>
        public bool CanTubeSign(string userid, string username)
        {
            ArrayList allList = GetQmList("普通医师签名");
            if (allList != null && allList.Count > 0)
            {
                ZYTextInput _input = allList[allList.Count - 1] as ZYTextInput;
                if (App.IsNeedCheck(_input.ID) || _input.ID != this.Us.InpatientInfo.Sick_Doctor_Id)
                {
                    foreach (ZYTextInput _childInput in allList)
                    {
                        if (_childInput.ID == this.Us.InpatientInfo.Sick_Doctor_Id)
                        {
                            App.Msg("已有管床医生签名！");
                            return true;
                        }
                    }
                    ZYTextInput newInput = new ZYTextInput();
                    newInput.OwnerDocument = this;
                    newInput.ID = userid;
                    newInput.Name = "普通医师签名";
                    newInput.Text = "        " + username;
                    newInput.CanDelete = true;
                    this._InsertSignature(newInput, _input);
                    this.SaveTrue = true;
                    this.ContentChanged();
                }
            }
            return true;
        }

        public bool CanTubeSign(string userid, string username, int type)
        {
            List<ZYTextInput> list = GetQmList();
            if (list != null && list.Count > 0)
            {
                foreach (ZYTextInput qmInput in list)
                {
                    if (qmInput.Name == "管床医师签名" && qmInput.ID != userid)
                    {
                        qmInput.Text = "        " + username;
                        qmInput.ID = userid;
                        this.SaveTrue = true;
                        this.ContentChanged();
                        return true;
                    }
                }

            }
            return true;
        }

        /***
         * 是否有上级医生签名
         */
        public bool HaveSuperiorSign(bool isSubmit)
        {
            if (isSubmit == false)
            {
                return false;
            }
            ArrayList arrList = this.GetQmList("普通医师签名");
            if (arrList != null && arrList.Count >= 1)
            {
                ZYTextInput qmLast = arrList[0] as ZYTextInput;
                if (App.IsHigherMasterDoctor(qmLast.ID))
                {
                    return true;
                }
            }
            return false;
        }


        /***
         * 第一种签名方式
         */
        public bool isHaveTextId()
        {
            if (this.isAutograph || this.Us.TextKind_id == 125 || this.Us.TextKind_id == 126 || this.Us.TextKind_id == 127
                || this.Us.TextKind_id == 128 || this.Us.TextKind_id == 130 || this.Us.TextKind_id == 131
                || this.Us.TextKind_id == 132 || this.Us.TextKind_id == 133 || this.Us.TextKind_id == 844
                || this.Us.TextKind_id == 135 || this.Us.TextKind_id == 136 || this.Us.TextKind_id == 139
                || this.Us.TextKind_id == 140 || this.Us.TextKind_id == 301 || this.Us.TextKind_id == 741
                || this.Us.TextKind_id == 761 || this.Us.TextKind_id == 861 || this.Us.TextKind_id == 862
                || this.Us.TextKind_id == 890 || this.Us.TextKind_id == 891 || this.Us.TextKind_id == 882
                || this.Us.TextKind_id == 153 || this.Us.TextKind_id == 150 || this.Us.TextKind_id == 1061
                || this.Us.TextKind_id == 157
                || this.Us.TextKind_id == 1162 || this.Us.TextKind_id == 1161 || this.Us.TextKind_id == 723
                || this.Us.TextKind_id == 1022 || this.Us.TextKind_id == 1201 || this.Us.TextKind_id == 1162)
            {
                return true;
            }
            return false;
        }

        /***
        * 第一种签名方式
        */
        public bool isHaveTextId(int t_textId)
        {
            if (t_textId == 125 || t_textId == 126 || t_textId == 127
                || t_textId == 128 || t_textId == 130 || t_textId == 131
                || t_textId == 132 || t_textId == 133 || t_textId == 844
                || t_textId == 135 || t_textId == 136 || t_textId == 139
                || t_textId == 140 || t_textId == 301 || t_textId == 741
                || t_textId == 761 || t_textId == 861 || t_textId == 862
                || t_textId == 890 || t_textId == 891 || t_textId == 882
                || t_textId == 153 || t_textId == 150 || t_textId == 1061
                )
            {
                return true;
            }
            return false;
        }

        /***
        * 其他文书签名
        */
        public bool _otherTextSign()
        {
            ArrayList list = this.GetQmList("签名集合"); //签名输入框集合
            if (list == null)
                return true;
            if (list != null)
            {
                ZYTextInput input2 = (ZYTextInput)list[0];
                if (!this.Locked)
                {
                    ArrayList list2 = new ArrayList();
                    foreach (ZYTextElement element in input2.ChildElements)
                    {
                        if (element is ZYTextInput)
                        {
                            list2.Add(element);
                        }
                    }

                    if (list2.Count > 0)
                    {

                        ZYTextInput input = (ZYTextInput)list2[0];
                        if (input.ID == App.UserAccount.UserInfo.User_id) //如果签名ID = 登录ID true
                        {
                            return true;
                        }

                        string hightId = App.GetTheHighLevelUserId(input.ID, App.UserAccount.UserInfo.User_id);
                        if (hightId == App.UserAccount.UserInfo.User_id)
                        {
                            ZYTextInput _input = new ZYTextInput();
                            _input.OwnerDocument = this;
                            _input.Name = "普通医师签名";
                            //医师姓名
                            _input.Text = "        " + App.UserAccount.UserInfo.User_name;
                            //医师ID
                            _input.ID = App.UserAccount.UserInfo.User_id;
                            _input.CanDelete = true;
                            _input.Parent = input2;
                            input2.ChildElements.Insert(input2.ChildElements.IndexOf(input), _input);
                            return true;
                        }
                        else
                        {
                            App.Msg("您登录账号的级别不够！");
                            return false;
                        }
                    }
                    else
                    {
                        ZYTextInput _input = new ZYTextInput();
                        _input.OwnerDocument = this;
                        _input.Name = "普通医师签名";
                        //医师姓名
                        _input.Text = "        " + App.UserAccount.UserInfo.User_name;
                        //医师ID
                        _input.ID = App.UserAccount.UserInfo.User_id;
                        _input.CanDelete = true;
                        _input.Parent = input2;
                        input2.ChildElements.Insert(0, _input);
                    }
                    this.ContentChanged();
                }
            }
            return true;
        }

        /// <summary>
        /// 插入病案评分
        /// </summary>
        /// <param name="id"></param>
        /// <param name="text"></param>
        public void InsertBAPF(string id, string text)
        {
            ZYTextBapfMark zc = new ZYTextBapfMark();
            zc.OwnerDocument = this;
            zc.Value = id;
            zc.CanDelete = true;
            zc.Sign = text;
            zc.ExcuteAdd();
            _InsertElement(zc);
            this.ContentChanged();
        }

        public void _InsertNumInput(float x, float x1)
        {
            if (this.Locked)
            {
                return;
            }
            this.BeginUpdate();
            this.BeginContentChangeLog();
            if (this.myContent.HasSelected())
            {
                this.myContent.DeleteSeleciton();
            }
            else if (!this.myOwnerControl.InsertMode)
            {
                this.myContent.DeleteCurrentElement();
            }
            ZYTextNumInput newElement = new ZYTextNumInput();
            newElement.MinNumber = x;
            newElement.MaxNumber = x1;
            newElement.OwnerDocument = this;
            this.myContent.InsertElement(newElement);
            this.myContentChangeLog.strUndoName = "插入域 ";
            this.EndContentChangeLog();
            this.EndUpdate();
        }

        /// <summary>
        /// 插入元素
        /// </summary>
        /// <param name="NewElement"></param>
        private void _InsertElement(ZYTextBapfMark NewElement)
        {
            this.BeginUpdate();
            this.BeginContentChangeLog();
            this.myContent.AutoClearSelection = true;
            this.myContent.InsertElement(NewElement);
            this.myContentChangeLog.strUndoName = "插入元素";
            this.myContent.MoveSelectStart((int)(this.myContent.SelectStart));
            this.EndContentChangeLog();
            this.EndUpdate();
        }

        public bool Automaticsignature(string user_id, string user_text, string _type)
        {
            bool isSignOk = false;
            if (this.isHaveTextId()) //自动带签名框上去
            {
                ArrayList list = GetQmList("普通医师签名"); //普通医师签名
                if (list != null)
                {
                    ZYTextInput maxInput = (ZYTextInput)list[0]; //获取最左边的签名
                    ZYTextInput minInput = (ZYTextInput)list[list.Count - 1]; //最右边的签名
                    if (maxInput.ID == user_id)  //如果最左边的签名 == user_id  返回true
                    {
                        isSignOk = true;
                        goto end;
                    }

                    if (App.IsNeedCheck(maxInput.ID))
                    {
                        if (user_id == this.Us.InpatientInfo.Sick_Doctor_Id)
                        {
                            ZYTextInput _input = new ZYTextInput();
                            _input.OwnerDocument = this;
                            _input.Name = "普通医师签名";
                            //医师姓名
                            _input.Text = "        " + user_text;
                            //医师ID
                            _input.ID = user_id;
                            _input.CanDelete = true;
                            _InsertSignature(_input, maxInput);
                            isSignOk = true;
                            goto end;
                        }
                        else
                        {
                            Class_DocSign cd = App.InSerterHighLevelSign("D"); //管床医师签名输入
                            if (cd != null)
                            {
                                if (cd.Userid == this.Us.InpatientInfo.Sick_Doctor_Id) //如果管床医师签名等于== 输入的签名
                                {
                                    ZYTextInput _input = new ZYTextInput();
                                    _input.OwnerDocument = this;
                                    _input.Name = "普通医师签名";
                                    //医师姓名
                                    _input.Text = "        " + user_text;
                                    //医师ID
                                    _input.ID = user_id;
                                    _input.CanDelete = true;
                                    _InsertSignature(_input, maxInput);
                                    isSignOk = true;
                                    goto end;
                                }
                                else //不等于
                                {
                                    App.Msg("您输入的账号不是该病人管床医生账号！");
                                    isSignOk = false;
                                    goto end;
                                }
                            }
                            goto end;
                        }
                    }

                    //左边的签名!=user_id
                    string hightId = App.GetTheHighLevelUserId(maxInput.ID, user_id); //左边的签名与user_id比较
                    if (hightId == user_id) //如果登录账号大于左边签名
                    {
                        if (this.SuporSign != "")  //上级查房ID
                        {
                            if (user_id != this.SuporSign)  //如果上级查房ID不等于user_id
                            {
                                string signId = App.GetTheHighLevelUserId(
                                    this.SuporSign, user_id); //将上级查房ID与user_id比较
                                if (signId == user_id)        //如果登录ID大于上级ID
                                {
                                    App.Msg(_type + "账号级别超过上级查房医师级别！");
                                    isSignOk = false;
                                    goto end;
                                }
                            }
                        }
                        ZYTextInput _input = new ZYTextInput();
                        _input.OwnerDocument = this;
                        _input.Name = "普通医师签名";
                        //医师姓名
                        _input.Text = "        " + user_text;
                        //医师ID
                        _input.ID = user_id;
                        _input.CanDelete = true;
                        _InsertSignature(_input, maxInput);
                        isSignOk = true;
                        goto end;
                    }
                    else
                    {
                        Class_DocSign cd = App.InSerterHighLevelSign(); //上级医师签名
                        if (cd != null)
                        {
                            string lastSignId2 = App.GetTheHighLevelUserId(maxInput.ID, cd.Userid); //输入的id与管床id比较
                            if (lastSignId2 == cd.Userid)
                            {
                                ZYTextInput _input = new ZYTextInput();
                                _input.OwnerDocument = this;
                                _input.Name = "普通医师签名";
                                //医师姓名
                                _input.Text = "        " + cd.Username;
                                //医师ID
                                _input.ID = cd.Userid;
                                _input.CanDelete = true;
                                _InsertSignature(_input, maxInput);
                                isSignOk = true;
                                goto end;
                            }
                            else
                            {
                                App.Msg("您输入的账号小于当前签名级别最高账号！");
                                isSignOk = false;
                                goto end;
                            }
                        }
                        goto end;
                    }
                }
                else
                {
                    ZYTextInput input;
                    input = new ZYTextInput();
                    input.OwnerDocument = this;
                    input.Name = "普通医师签名";
                    input.Text = "        " + user_text;  //user_text
                    input.ID = user_id;                   //user_id
                    input.CanDelete = true;
                    ZYTextElement element = (ZYTextElement)this.Elements[this.Elements.Count - 1]; //最后一个元素
                    ArrayList arr = new ArrayList();
                    if (element is ZYTextParagraph && element.Parent == this.myDocumentElement) //判断最后一行是否只有一个元素
                    {
                        ZYTextParagraph ztp = (ZYTextParagraph)element;
                        if (ztp.OwnerLine.Elements.Count > 1)
                        {
                            ZYTextParagraph ztp2 = new ZYTextParagraph();
                            ztp2.OwnerDocument = this;
                            arr.Add(ztp2);
                        }
                        arr.Add(input);
                        ztp.RightAlign = true;
                        this.myDocumentElement.InsertRangeBefore(arr, ztp); //将元素插入集合汇总
                        isSignOk = true;
                        goto end;
                    }
                }
            }
            else
            {
                List<ZYTextInput> list = this.GetQmList(); //签名输入框集合
                if (list != null) //集合数量大于0
                {
                    ZYTextInput ptQm = null;
                    ZYTextInput gcQm = null;
                    ZYTextInput sjQm = null;
                    foreach (ZYTextInput _input in list)
                    {
                        if (_input.Name == "普通医师签名") //普通医师签名框
                        {
                            ptQm = _input;
                        }
                        else if (_input.Name == "管床医师签名") //管床医师签名框
                        {
                            gcQm = _input;
                        }
                        else if (_input.Name == "上级医师签名") //上级医师签名框
                        {
                            sjQm = _input;
                        }
                    }

                    //上级医师签名
                    if (sjQm != null && sjQm.Text.Length > 5 && sjQm.ID != "") //如果存在上级医师签名
                    {
                        if (sjQm.ID == user_id) //如果上级签名ID = user_id
                        {
                            isSignOk = true;
                            goto end;
                        }
                        App.Msg("已存在上级医师签名，只有签名的上级医师才能修改保存！");
                        isSignOk = false;
                        goto end;
                    }

                    //管床医师签名
                    if (gcQm != null && gcQm.Text.Length > 5 && gcQm.ID != "")
                    {
                        if (gcQm.ID == user_id)
                        {
                            isSignOk = true;
                            goto end;
                        }
                        else
                        {
                            if (sjQm != null)
                            {
                                string lastSignId4 = App.GetTheHighLevelUserId(ptQm.ID, user_id); //普通签名与输入签名比较
                                if (lastSignId4 == user_id && App.IsHigherMasterDoctor(user_id))
                                {
                                    sjQm.ID = user_id;
                                    sjQm.Text = "        " + user_text;
                                    isSignOk = true;
                                    goto end;
                                }
                                else
                                {
                                    Class_DocSign cd = App.InSerterHighLevelSign(); //上级医师签名输入
                                    if (cd != null)
                                    {
                                        string lastSignId3 = App.GetTheHighLevelUserId(ptQm.ID, cd.Userid); //普通签名与输入签名比较
                                        if (lastSignId3 == cd.Userid && App.IsHigherMasterDoctor(cd.Userid))
                                        {
                                            sjQm.ID = cd.Userid;
                                            sjQm.Text = "        " + cd.Username;
                                            isSignOk = true;
                                            goto end;
                                        }
                                        else
                                        {
                                            App.Msg("您输入的级别不够！");
                                            isSignOk = false;
                                            goto end;
                                        }
                                    }
                                    goto end;
                                }
                            }
                        }
                    }

                    if (ptQm != null)  //普通医师签名
                    {
                        if (ptQm.ID != "" && ptQm.Text.Length > 5) //id有效
                        {
                            if (ptQm.ID == user_id) //如果记录者签名 = user_id
                            {
                                isSignOk = true;
                                goto end;
                            }

                            if (App.IsNeedCheck(ptQm.ID) && gcQm != null) //如果是 研究生 无证住院医师 实习生签名
                            {
                                if (user_id == this.Us.InpatientInfo.Sick_Doctor_Id && gcQm != null)
                                {
                                    gcQm.ID = user_id;
                                    gcQm.Text = user_text;
                                    isSignOk = true;
                                    goto end;
                                }

                                Class_DocSign cd = App.InSerterHighLevelSign("D"); //管床医师签名输入
                                if (cd != null)
                                {
                                    if (cd.Userid == this.Us.InpatientInfo.Sick_Doctor_Id) //如果管床医师签名等于== 输入的签名
                                    {
                                        gcQm.ID = cd.Userid;
                                        gcQm.Text = "        " + cd.Username;
                                        isSignOk = true;
                                        goto end;
                                    }
                                    else //不等于
                                    {
                                        App.Msg("您输入的账号不是该病人管床医生账号！");
                                        isSignOk = false;
                                        goto end;
                                    }
                                }
                                goto end;
                            }
                            else
                            {
                                if (sjQm != null)
                                {
                                    string lastSignId4 = App.GetTheHighLevelUserId(ptQm.ID, user_id); //普通签名与输入签名比较
                                    if (lastSignId4 == user_id && App.IsHigherMasterDoctor(user_id))
                                    {
                                        sjQm.ID = user_id;
                                        sjQm.Text = "        " + user_text;
                                        isSignOk = true;
                                        goto end;
                                    }
                                    else
                                    {
                                        Class_DocSign cd = App.InSerterHighLevelSign(); //上级医师签名输入
                                        if (cd != null)
                                        {
                                            string lastSignId3 = App.GetTheHighLevelUserId(ptQm.ID, cd.Userid); //普通签名与输入签名比较
                                            if (lastSignId3 == cd.Userid && App.IsHigherMasterDoctor(cd.Userid))
                                            {
                                                sjQm.ID = cd.Userid;
                                                sjQm.Text = "        " + cd.Username;
                                                isSignOk = true;
                                                goto end;
                                            }
                                            else
                                            {
                                                App.Msg("您输入的账号级别不够！");
                                                isSignOk = false;
                                                goto end;
                                            }
                                        }
                                        goto end;
                                    }
                                }
                            }
                        }
                        else
                        {
                            ptQm.Text = "        " + user_text; //普通签名
                            ptQm.ID = user_id;
                            isSignOk = true;
                            goto end;
                        }
                    }
                }
                else
                {
                    isSignOk = false;
                    goto end;
                }
            }
        end:
            this.ContentChanged();
            return isSignOk;
        }

        /// <summary>
        /// 过滤模板
        /// </summary>
        /// <param name="loadXml"></param>
        public void FilterXml(string loadXml, int style, XmlNode docsetting)
        {
            XmlDocument document = new XmlDocument();
            document.PreserveWhitespace = true;
            document.LoadXml("<emrtextdoc/>");
            if (this.ToXML(document.DocumentElement) && this.isHaveTextId())
            {
                if (style == 1)
                {
                    XmlNodeList list = document.GetElementsByTagName("div");
                    if (list.Count > 0)
                    {
                        foreach (XmlNode xn in list)
                        {
                            foreach (XmlAttribute atb in xn.Attributes)
                            {
                                if (atb.Name == "timeTitle" && atb.Value == "Y")
                                {

                                    loadXml = xn.OuterXml + loadXml;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            XmlDocument xmlDoc = new XmlDocument();//加入XML的声明段落   
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml("<emrtextdoc/>");
            string strXml = GetXmlContent();
            xmlDoc.LoadXml(strXml);
            XmlNode xmlNode = xmlDoc.SelectSingleNode("emrtextdoc");//查找<body>                
            foreach (XmlElement bodyNode in xmlNode.ChildNodes)
            {
                if (bodyNode.Name == "body")
                {
                    bodyNode.InnerXml = loadXml;
                }
                if (docsetting != null && bodyNode.Name == "docsetting")
                {
                    bodyNode.RemoveAllAttributes();
                    foreach (XmlAttribute _attribute in docsetting.Attributes)
                    {
                        bodyNode.SetAttribute(_attribute.Name, _attribute.Value);
                    }
                }
            }
            this.FromXML(xmlDoc.DocumentElement);
        }

        public void FilterXml(string loadXml, XmlDocument fileDocument, int style)
        {
            this.FromXML(fileDocument.DocumentElement);
        }

        private bool _enableHide = false;

        public bool EnableHide
        {
            get { return _enableHide; }
            set { _enableHide = value; }
        }

        private bool isDrawBack = false;
        public void PrintEdit(object sender, EventArgs e)
        {
            if ((this.Us.Tid == 0 || this.Modified) && !this.Locked)
            {
                App.Msg("请先保存再打印");
                return;
            }
            try
            {
                this.myInfo.Printing = true;
                this.RefreshSize();
                this.RefreshLine();
                this.EnableHide = true;
                this.RefreshElements();
                this.RefreshSize();
                this.RefreshLine();
                this.EnableHide = false;
                if (this.EnableJumpPrint)
                {
                    if (this.JumpElement.Deleteted)
                    {
                        while (this.myContent.CurrentElement.Deleteted)
                        {
                            if (this.Elements.IndexOf(this.myContent.CurrentElement) >= this.Elements.Count - 1)
                            {
                                break;
                            }
                            if (this.myContent.CurrentElement is ZYTextBlock)
                            {
                                this.myContent.intSelectStart = this.Elements.IndexOf(this.myContent.CurrentElement) + ((ZYTextBlock)this.myContent.CurrentElement).ChildCount + 1;
                            }
                            else
                                this.myContent.intSelectStart = this.Elements.IndexOf(this.myContent.CurrentElement) + 1;
                        }
                        this.jumpElement = this.myContent.CurrentElement;
                    }
                }
                isDrawBack = true;
                frmDocPrint fdp = new frmDocPrint(this, this.myView, this.myPages, this.myInfo);
                fdp.ShowDialog();
                fdp.Dispose();
                isDrawBack = false;
            }
            catch (Exception e2)
            {
                App.Msg(e2.Message + " 1.确认Print Spooler服务开启。2.是否设置默认打印机");
            }
            finally
            {
                if (!this.Locked)
                {
                    this.Info.ShowExpendHandle = true;
                    this.Info.ShowParagraphFlag = true;
                    this.Info.FieldUnderLine = true;
                    this.myInfo.Printing = false;
                    this.RefreshSize();
                    this.RefreshLine();
                }
            }
            this.ContentChanged();
        }

        //public void firstList(string _action)
        //{
        //    try
        //    {
        //        if (_action == "上级医师查房记录")
        //        {
        //            string sql
        //        = String.Format("SELECT T.DOC_NAME,T.TID FROM T_PATIENTS_DOC T WHERE T.PATIENT_ID = '{0}' AND T.TEXTKIND_ID = '127' AND T.SUBMITTED = 'Y' ORDER BY T.DOC_NAME ", Us.InpatientInfo.Id);
        //            DataTable dtSJCF = App.GetDataSet(sql).Tables[0];
        //            if (dtSJCF != null && dtSJCF.Rows.Count > 0)
        //            {
        //                frmSJCF cf = new frmSJCF(dtSJCF);
        //                cf.ShowDialog();
        //                if (cf.XmlString != "")
        //                {
        //                    string content = App.DownLoadFtpPatientDoc(cf.XmlString + ".xml", this.Us.InpatientInfo.Id.ToString());
        //                    XmlDocument _document = new XmlDocument();
        //                    _document.PreserveWhitespace = true;
        //                    _document.LoadXml(content);
        //                    XmlNodeList selectNodeList = _document.GetElementsByTagName("body");
        //                    if (selectNodeList != null && selectNodeList.Count > 0)
        //                    {
        //                        StringBuilder strBuild = new StringBuilder();
        //                        XmlNode nodes = selectNodeList[0];
        //                        foreach (XmlNode node in nodes.ChildNodes)
        //                        {
        //                            if (node.Name == "div")
        //                            {
        //                                if (node.Attributes["timeTitle"] != null && node.Attributes["timeTitle"].Value.ToLower() == "y")
        //                                {
        //                                    continue;
        //                                }
        //                            }
        //                            if (node.Name == "input")
        //                            {
        //                                if (node.Attributes["name"] != null && node.Attributes["name"].Value == "普通医师签名")
        //                                {
        //                                    break;
        //                                }
        //                            }
        //                            strBuild.Append(node.OuterXml);
        //                        }
        //                        if (strBuild.Length > 0)
        //                        {
        //                            this._insertElements("<body>" + strBuild.ToString() + "</body>");
        //                        }
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                App.Msg("无上级医师查房记录！");
        //            }
        //        }
        //        else
        //        {
        //            string sql = String.Format("SELECT T.tid FROM T_PATIENTS_DOC T WHERE T.TEXTKIND_ID = '119' AND T.PATIENT_ID = '{0}'", this.Us.InpatientInfo.Id);
        //            DataTable dt = App.GetDataSet(sql).Tables[0];
        //            if (dt == null || dt.Rows.Count < 1)
        //            {
        //                return;
        //            }
        //            string nodeXMl = string.Empty;
        //            string content = App.DownLoadFtpPatientDoc(dt.Rows[0][0].ToString() + ".xml", this.Us.InpatientInfo.Id.ToString());
        //            if (!string.IsNullOrEmpty(content))
        //            {
        //                XmlDocument document = new XmlDocument();
        //                document.PreserveWhitespace = true;
        //                document.LoadXml(content);
        //                XmlDocument newDocument = new XmlDocument();
        //                newDocument.PreserveWhitespace = true;
        //                newDocument.LoadXml("<emrtextdocument2005/>");
        //                CreateNewXml(newDocument.DocumentElement, document.DocumentElement, 10);
        //                XmlNodeList list = newDocument.GetElementsByTagName("div");
        //                if (list != null && list.Count > 0)
        //                {
        //                    foreach (XmlNode node in list)
        //                    {
        //                        if (node.Attributes["title"] != null)
        //                        {
        //                            string title = node.Attributes["title"].Value;
        //                            if (title.Contains(_action))
        //                            {
        //                                nodeXMl = node.InnerXml;
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                App.Msg("没有找到" + _action);
        //            }
        //            if (!string.IsNullOrEmpty(nodeXMl))
        //            {
        //                _insertElements(string.Format("<insert>{0}</insert>", nodeXMl));
        //            }
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        App.Msg(e.Message);
        //    }
        //}

        public void firstList(string _action)
        {
            try
            {
                if (_action == "上级医师查房记录")
                {
                    string sql
                = String.Format("SELECT T.DOC_NAME,T.TID FROM T_PATIENTS_DOC T WHERE T.PATIENT_ID = '{0}' AND T.TEXTKIND_ID = '127' AND T.SUBMITTED = 'Y' ORDER BY T.DOC_NAME ", Us.InpatientInfo.Id);
                    DataTable dtSJCF = App.GetDataSet(sql).Tables[0];
                    if (dtSJCF != null && dtSJCF.Rows.Count > 0)
                    {
                        frmSJCF cf = new frmSJCF(dtSJCF);
                        cf.ShowDialog();
                        if (cf.XmlString != "")
                        {
                            string content = App.DownLoadFtpPatientDoc(cf.XmlString + ".xml", this.Us.InpatientInfo.Id.ToString());
                            XmlDocument _document = new XmlDocument();
                            _document.PreserveWhitespace = true;
                            _document.LoadXml(content);
                            XmlNodeList selectNodeList = _document.GetElementsByTagName("body");
                            if (selectNodeList != null && selectNodeList.Count > 0)
                            {
                                StringBuilder strBuild = new StringBuilder();
                                XmlNode nodes = selectNodeList[0];
                                foreach (XmlNode node in nodes.ChildNodes)
                                {
                                    if (node.Name == "div")
                                    {
                                        if (node.Attributes["timeTitle"] != null && node.Attributes["timeTitle"].Value.ToLower() == "y")
                                        {
                                            continue;
                                        }
                                    }
                                    if (node.Name == "input")
                                    {
                                        if (node.Attributes["name"] != null && node.Attributes["name"].Value == "普通医师签名")
                                        {
                                            break;
                                        }
                                    }
                                    strBuild.Append(node.OuterXml);
                                }
                                if (strBuild.Length > 0)
                                {
                                    this._insertElements("<body>" + strBuild.ToString() + "</body>");
                                }
                            }
                        }
                    }
                    else
                    {
                        App.Msg("无上级医师查房记录！");
                    }
                }
                else
                {
                    //string sql = String.Format("SELECT T.tid FROM T_PATIENTS_DOC T WHERE T.TEXTKIND_ID = '119' AND T.PATIENT_ID = '{0}'", this.Us.InpatientInfo.Id);
                    string sql = String.Format("select b.tid,c.content from t_text_read a inner join " +
                                               " T_PATIENTS_DOC b on a.currenttid=b.textkind_id inner join " +
                                               " t_patient_doc_colb c on b.tid=c.tid where b.patient_id='{0}' and a.ctitlename='{1}'",
                                               this.Us.InpatientInfo.Id, _action);
                    DataTable dt = App.GetDataSet(sql).Tables[0];
                    if (dt == null || dt.Rows.Count < 1)
                    {
                        App.MsgWaring("当前病人没有" + _action + "信息");
                        return;
                    }
                    string nodeXMl = string.Empty;
                    //string content = App.DownLoadFtpPatientDoc(dt.Rows[0][0].ToString() + ".xml", this.Us.InpatientInfo.Id.ToString());
                    #region 查找有相关div的文书
                    string content = "";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        content = dt.Rows[i]["content"].ToString();
                        XmlDocument document = new XmlDocument();
                        document.PreserveWhitespace = true;
                        document.LoadXml(content);
                        XmlDocument newDocument = new XmlDocument();
                        XmlNodeList list = newDocument.GetElementsByTagName("div");
                        if (list != null && list.Count > 0)
                        {
                            foreach (XmlNode node in list)
                            {
                                if (node.Attributes["title"] != null)
                                {
                                    string title = node.Attributes["title"].Value;
                                    if (title.Contains(_action))
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    if (!string.IsNullOrEmpty(content))
                    {
                        XmlDocument document = new XmlDocument();
                        document.PreserveWhitespace = true;
                        document.LoadXml(content);
                        XmlDocument newDocument = new XmlDocument();
                        newDocument.PreserveWhitespace = true;
                        newDocument.LoadXml("<emrtextdocument2005/>");
                        CreateNewXml(newDocument.DocumentElement, document.DocumentElement, 10);
                        XmlNodeList list = newDocument.GetElementsByTagName("div");
                        if (list != null && list.Count > 0)
                        {
                            foreach (XmlNode node in list)
                            {
                                if (node.Attributes["title"] != null)
                                {
                                    string title = node.Attributes["title"].Value;
                                    if (title.Contains(_action))
                                    {
                                        nodeXMl = node.InnerXml;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        App.Msg("没有找到" + _action);
                    }
                    if (!string.IsNullOrEmpty(nodeXMl))
                    {
                        _insertElements(string.Format("<insert>{0}</insert>", nodeXMl));
                    }
                }
            }
            catch (Exception e)
            {
                App.Msg(e.Message);
            }
        }

        public void _insertElements(string xmlBuild)
        {
            XmlDocument ChildNodexml = new XmlDocument();
            ChildNodexml.PreserveWhitespace = true;
            ChildNodexml.LoadXml(xmlBuild);
            ArrayList newList = new ArrayList();
            this.LoadElementsToList(ChildNodexml.DocumentElement, newList);
            if (newList.Count > 0)
            {
                this.BeginUpdate();
                this.BeginContentChangeLog();
                this.Content.InsertRangeElements(newList);
                this.EndContentChangeLog();
                this.EndUpdate();
            }
        }

        public bool isDraught = false;
        /***
         * 判断是否管床医生审签
         * 1.改文书是否需要审签
         *  1.已审签 
         *  2.未审签 页面打印草稿两字
         * 2.不需要跳过
         */
        public bool PrintDraught()
        {
            isDraught = false;
            if (this.TextSuperiorSignature == "Y")
            {
                if (this.isHaveTextId())
                {
                    ArrayList qmList = this.GetQmList("普通医师签名");
                    if (qmList != null && qmList.Count == 1)
                    {
                        isDraught = true;
                        return false;
                    }
                }
                else
                {
                    List<ZYTextInput> qmList = this.GetQmList();
                    ZYTextInput ptQm = null;
                    ZYTextInput sjQM = null;
                    foreach (ZYTextInput _input in qmList)
                    {
                        if (_input.Name == "普通医师签名")
                        {
                            ptQm = _input;
                        }
                        else if (_input.Name == "上级医师签名")
                        {
                            sjQM = _input;
                        }
                    }

                    if (sjQM.Text.Length < 5)
                    {
                        isDraught = true;
                        return false;
                    }

                    if (ptQm != null && ptQm.Text.Length > 5)
                    {
                        if (App.IsNeedCheck(ptQm.ID))
                        {
                            if (sjQM == null || sjQM.Text.Length < 5)
                            {
                                isDraught = true;
                            }
                        }
                    }
                }
            }
            return true;
        }

        private static MemoryStream GetStream(ArrayList Images, System.IO.MemoryStream mstream, Bitmap bitmap)
        {
            mstream = new System.IO.MemoryStream();///创建内存流 
            bitmap.Save(mstream, ImageFormat.Gif);
            byte[] bytes = new byte[mstream.Length];
            bytes = mstream.ToArray();
            DataTable1 tempdate = new DataTable1();
            tempdate.image = bytes;
            Images.Add(tempdate);
            //App.UserAccount.UserInfo.U_tech_post
            return mstream;
        }

        private bool CanDragString()
        {
            return Math.Abs(this.Content.SelectLength) > 0 && !this.Locked && this.Content.GetSelectElements().IndexOf(this.Content.CurrentSelectElement) >= 0;
        }

        public void SetToolEvent()
        {
            App.A_Commit = null;
            App.A_Commit += new EventHandler(saveDocument);
            App.A_Print = null;
            App.A_Print += new EventHandler(PrintEdit);
            App.A_TempSave = null;
            App.A_TempSave += new EventHandler(saveDocument);
        }

        #region 文书或模板的保存
        /// <summary>
        /// 插入文书
        /// </summary>
        /// <param name="PID"></param>
        /// <param name="textKind_ID"></param>
        /// <param name="xmlDoc"></param>
        /// <param name="belongToSys_ID"></param>
        /// <param name="sickKind_ID"></param>
        /// <param name="textName"></param>
        /// <param name="_isTemporary"></param>
        /// <returns></returns>
        public string InsertModel(string PID, int textKind_ID, string xmlDoc, int belongToSys_ID, int sickKind_ID, string textName, bool _isTemporary)
        {
            try
            {
                ////设置 文书内容 XML 参数
                //Bifrost.WebReference.OracleParameter[] xmlParDoc = new Bifrost.WebReference.OracleParameter[1];
                //xmlParDoc[0] = new Bifrost.WebReference.OracleParameter();
                //xmlParDoc[0].ParameterName = "Patients_Doc";
                //xmlParDoc[0].Value = xmlDoc;
                //xmlParDoc[0].OracleType = OracleType.Clob;
                //int tid = App.GenId("T_Patients_Doc", "TID");
                //string strinsert =
                //    string.Format("insert into T_Patients_Doc(tid,CREATEID, pid, textkind_id, patients_doc, belongtosys_id, sickkind_id, textname,submitted,PATIENT_ID,DOC_NAME) " +
                //                  "values('{0}','{1}','{2}','{3}',:Patients_Doc,'{4}','{5}','{6}','{7}','{8}','{9}')"
                //                  , tid.ToString()                                                  //文书ID
                //                  , (_isTemporary == true ? App.UserAccount.UserInfo.User_id : "") //是否提交按钮
                //                  , PID
                //                  , textKind_ID
                //                  , belongToSys_ID
                //                  , sickKind_ID
                //                  , textName
                //                  , (_isTemporary == true ? "Y" : "N")  //暂存/提交
                //                  , Us.InpatientInfo.Id
                //                  , Us.RecordTime + "   " + Us.RecordText);
                ////如果保存文书成功
                //if (App.ExecuteSQL(strinsert, xmlParDoc) > 0)
                //{
                //    this.Us.Tid = tid;
                //    if (Us.IsMore)
                //    {
                //        if (this.Us.RecordTime == "")
                //        {
                //            this.Us.RecordTime = App.GetSystemTime().ToString("yyyy-MM-dd HH:mm");
                //        }
                //        string sql2 = string.Format(" insert into t_quality_text"
                //                                  + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
                //                                  + " values"
                //                                  + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')",
                //                                  Us.RecordTime + "   " + Us.RecordText
                //                                  , textKind_ID
                //                                  , Us.InpatientInfo.PId
                //                                  , Convert.ToDateTime(Us.RecordTime).ToString("yyyy-MM-dd HH:mm")
                //                                  , tid
                //                                  , Us.InpatientInfo.Id);
                //        if (App.ExecuteSQL(sql2) < 1)
                //        {
                //            App.Msg("质控表保存失败");
                //        }
                //    }
                //    else
                //    {
                //        string sql2 = string.Format(" insert into t_quality_text"
                //                                   + " (textname, TEXTTKIND_ID, pid, create_time,tid,PATIENT_ID)"
                //                                   + " values"
                //                                   + " ('{0}','{1}','{2}',to_TIMESTAMP('{3}','yyyy-MM-dd hh24:mi'),'{4}','{5}')",
                //                                   this.Us.TextName
                //                                   , textKind_ID
                //                                   , Us.InpatientInfo.PId
                //                                   , App.GetSystemTime().ToString("yyyy-MM-dd HH:mm")
                //                                   , tid
                //                                   , Us.InpatientInfo.Id);
                //        if (App.ExecuteSQL(sql2) < 1)
                //        {
                //            App.Msg("质控表保存失败");
                //        }
                //    }
                //}
                return "成功";
            }
            catch (Exception ex)
            {
                return "数据库异常！----------------" + ex.ToString();
            }
        }

        /// <summary>
        /// 插入标签模板
        /// </summary>
        /// <param name="doc">文书代码</param>
        /// <param name="xmlDoc">标签模板</param>
        /// <returns></returns>       
        public string InsertLableModel(int tid, string xmlDoc)
        {
            XmlDocument Doc = new XmlDocument();
            Doc.LoadXml(xmlDoc);
            XmlElement xmlElement = Doc.DocumentElement;
            string insertLable = "";
            int message = 0;
            try
            {
                foreach (XmlNode bodyNode in xmlElement.ChildNodes)
                {
                    if (bodyNode.Name == "body")
                    {
                        if (bodyNode.HasChildNodes)
                        {   //int i = 1;                        
                            foreach (XmlNode divNode in bodyNode.ChildNodes)
                            {
                                if (divNode.Name == "div")
                                {
                                    //i++;
                                    //string divModel = divNode.InnerText;
                                    string divTitle = "";
                                    for (int i = 0; i < divNode.Attributes.Count; i++)
                                    {
                                        if (divNode.Attributes[i].ToString().Trim() == "title")
                                            divTitle = divNode.Attributes["title"].Value;
                                    }

                                    if (divTitle.Trim() == "")
                                        divTitle = "文本域";
                                    int id = App.GenId("t_model_lable", "LID");
                                    //插入标签模块
                                    insertLable = "insert into t_model_lable(LID,TID,LABLEKIND,LABLE_MODEL)values(" + id + "," + tid + ",'" + divTitle + "',:divModel)";

                                    DBParameter[] xmlPars = new DBParameter[1];
                                    xmlPars[0] = new DBParameter();
                                    xmlPars[0].ParameterName = "divModel";
                                    xmlPars[0].Value = divNode.OuterXml;
                                    xmlPars[0].DBType = OracleDbType.Clob;
                                    //xmlPars[0].Direction = ParameterDirection.Input;
                                    message = App.ExecuteSQL(insertLable, xmlPars);
                                    if (message > 1)
                                    {
                                        ArrayList sqllist = new ArrayList();
                                        foreach (XmlNode selectNode in divNode.ChildNodes)
                                        {
                                            if (selectNode.Name == "select")
                                            {
                                                string selName = selectNode.Attributes["name"].Value;
                                                string selValue = selectNode.Attributes["value"].Value;
                                                string sid = App.GenId("t_struct", "sid").ToString();
                                                ////插入结构化
                                                string insertStruct = "insert into t_struct values(" + sid + "," + id + ",'" + selName + "','" + selValue + "'," + tid + ")";
                                                //message = ExecuteSQL(insertStruct);
                                                sqllist.Add(insertStruct);
                                            }
                                        }

                                        string[] sqls = new string[sqllist.Count];
                                        for (int i = 0; i < sqllist.Count; i++)
                                        {
                                            sqls[i] = sqllist[i].ToString();
                                        }

                                        App.ExecuteBatch(sqls);
                                    }
                                }
                            }
                        }
                    }
                }
                return "保存成功";
            }
            catch (Exception ex)
            {
                return "数据库异常！----------------" + ex.ToString();
            }
            finally
            {
            }
        }


        /// <summary>
        /// 插入标签模板
        /// </summary>
        /// <param name="doc">文书代码</param>
        /// <param name="xmlDoc">标签模板</param>
        /// <returns></returns>       
        public string InsertLableContent(int tid, string xmlDoc)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.LoadXml(xmlDoc);
            XmlElement xmlElement = doc.DocumentElement;
            string insertLable = "";
            int message = 0;
            try
            {
                foreach (XmlNode bodyNode in xmlElement.ChildNodes)
                {
                    if (bodyNode.Name == "body")
                    {
                        if (bodyNode.HasChildNodes)
                        {
                            string divTitle = "test";
                            int id = App.GenId("T_TempPlate_Cont", "ID");
                            //插入标签模块
                            insertLable = "insert into T_TempPlate_Cont(ID,TID,LableName,Content)values(" + id + "," + tid + ",'" + divTitle + "',:divContent)";
                            DBParameter[] xmlPars = new DBParameter[1];
                            xmlPars[0] = new DBParameter();
                            xmlPars[0].ParameterName = "divContent";
                            //xmlPars[0].Value = divNode.OuterXml;
                            xmlPars[0].Value = bodyNode.InnerXml;
                            xmlPars[0].DBType = OracleDbType.Clob;
                            xmlPars[0].Direction = Bifrost.WcfSvr.ParameterDirection.Input;
                            message = App.ExecuteSQL(insertLable, xmlPars);
                        }
                    }
                }

                if (message != 0)
                {
                    return "成功！";
                }
                else
                {
                    return "失败！";
                }
            }
            catch (Exception ex)
            {
                return "数据库异常！----------------" + ex.ToString();
            }
            finally
            {
                //NClose();
            }
        }
        #endregion

        class DataTable1
        {
            private string _name;
            public string name
            {
                get { return _name; }
                set { _name = value; }
            }

            private byte[] _image;
            public byte[] image
            {
                get { return _image; }
                set { _image = value; }
            }
        }

        public void Method()
        {
            throw new System.NotImplementedException();
        }
    }
}

